如何像在Java中的词法分析器中那样标记字符串?

我要根据词法分析器规则标记化的代码行。

  String input1 = input.replaceAll("\\s+"," ");

     List<String> uncleanList = Arrays.asList(input1.split(" "));

我将此代码放在String中。 将所有多个空格替换为一个空格

String s = codeString.replaceAll("\\s+"," ");

然后

  String t= s.split(" ") 
该字符串上的

方法借助单个空格为我提供了一个数组。 我得到了这个数组结果(这是System.out.println(Arrays.toString(s));的控制台输出):

[String,input1,=,input.replaceAll("\\s+",",");,List<String>,uncleanList,Arrays.asList(input1.split(","));]

,但有很多()方括号。点“”等,不留空格。现在我被困在这里。如何在单独的索引上将符号与字母或数字分开。

在控制台上打印阵列时所需的阵列输出:

 [String,input,.,replaceAll,(,"\\s+"," ",),;,List,<,String,>,Arrays,asList,split,]   
giggs361 回答:如何像在Java中的词法分析器中那样标记字符串?

当没有定界符可使用时,split不再是进行令牌化的有效方法。与其使用split查找不需要的部件,不如使用find查找所需的部件,如下所示:

Pattern pattern = Pattern.compile("\\w+|[+-]?[0-9\\._Ee]+|\\S");
Matcher matcher = pattern.matcher(input);

// Find all matches
while (matcher.find()) {
  String token = matcher.group();
}

我在这里提供的示例正则表达式比您真正想要的简单。重要的是,您提供了默认模式(\ S)以匹配较长匹配中不包含的任何非空白字符。这将处理所有单字符令牌。

您必须匹配的一些较长的令牌(例如字符串和注释)非常复杂,因此需要一些工作才能使此正确。

本文链接:https://www.f2er.com/3078611.html

大家都在问