我正在尝试匹配字符串文本中的某些关键字。关键字可以包含特殊字符的任意组合,并且必须是整个单词(不含空格)。
public static void main(String[] args)
{
String words[] = {"Hello", "World", "£999.00", "*&332", "$30,00", "$1230.30",
"Apple^*$Banana&$Pears!$", "90.09%"};
String text = "Hello world World £99900 £999.00 Apple^*$Banana&$Pears!$"
+ " $30,00 *&332 $1230.30 90.09%";
StringBuilder regex = new StringBuilder();
regex.append("(");
for(String item : word)
regex.append("(?:^|\\s)").append(item).append("(?:$|\\s)").append("|");
regex.deleteCharAt(buildRegex.length() - 1);
regex.append(")");
Pattern pattern = Pattern.compile(regex.toString());
Matcher match = pattern.matcher(text);
while (match.find())
System.out.println(match.group());
}
我得到的结果是:
你好
世界
999.00英镑
&332
90.09%
并非所有单词都匹配。我尝试了此处发布的不同解决方案,并且进行搜索,但无法匹配我的示例中的所有单词。
如何匹配包含任意特殊字符组合的关键字?
最佳答案
这个基于lookaround
的正则表达式应该可以工作:
for(String item : words)
regex.append("(?<=^|\\s)").append(Pattern.quote(item)).append("(?=\\s|$)").append("|");
主要区别是:
- 使用环顾四周以避免匹配空格。当找到两个连续的匹配项时,这会在正则表达式中产生问题,因为空间已经被消耗。
- 使用
Pattern.quote
来处理特殊字符
这会得到输出:
Hello
World
£999.00
Apple^*$Banana&$Pears!$
$30,00
*&332
$1230.30
90.09%
关于Java正则表达式匹配包含特殊字符的整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21933704/