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

问题描述 投票:-3回答:1

要标记化的Java代码:

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

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

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

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

然后

  String t= s.split(" ") 

该字符串上的方法在单个空格的帮助下为我提供了一个数组。我得到了这个数组结果:

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

所需的数组输出:

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

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

java regex algorithm token tokenize
1个回答
1
投票

[当没有定界符使用时,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)以匹配较长匹配中不包含的任何非空白字符。这将处理所有单字符令牌。

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

© www.soinside.com 2019 - 2024. All rights reserved.