我正在尝试创建一个 Matcher 实例以从字符串中提取 token 。这是我使用的:
Matcher base = Pattern.compile("red|green|blue|\\+|\\(|\\)").matcher(input.trim());
while (!base.hitEnd()) {
if (base.find()) {
String s = base.group();
output += String.format(" %s", s);
}
else {
throw new IllegalArgumentException("Invalid tokens in the input! " + base.toString());
}
}
在这种情况下,input
是我要标记化的输入字符串。但是,即使我给它输入“red”,它仍然会抛出异常,并显示该对象没有尝试匹配(没有更改正在考虑的索引,没有先前的匹配)。
我的目标是匹配确切的单词“red”、“green”、“blue”
、加号以及左括号和右括号作为标记。我错过了什么?
最佳答案
如果我理解正确的话,当没有找到您要查找的标记时,您想抛出异常。对您所做的修改将正确找到您正在查找的标记,如果输入字符串不包含任何标记,则抛出异常。
Matcher base = Pattern.compile("\\bred\\b|\\bgreen\\b|\\bblue\\b|[+()]{1}").matcher(input.trim());
while (!base.hitEnd()) {
if (base.find()) {
String s = base.group();
System.out.println("Found: " + s);
output += String.format(" %s", s);
}
}
if (output.isEmpty()) {
throw new IllegalArgumentException("Invalid input no matching tokens found! " + base.toString());
}
我更新了你的正则表达式中的一些内容。我为 red、green、blue
周围的单词边界添加了 \\b
,并将 +()
组合成一个字符组。字符组将与 []
中的任何字符完全匹配。
关于Java 的 Matcher 无法正确匹配输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23532122/