Java正则表达式匹配包含特殊字符的整个单词

标签 java regex string escaping match

我正在尝试匹配字符串文本中的某些关键字。关键字可以包含特殊字符的任意组合,并且必须是整个单词(不含空格)。

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/

相关文章:

php如何获取特定位置的字符串

c - 从 C 中的字符串中获取子字符串

python - 从 python 中的不同字符串生成 'random' 字符串?

java - 自引用通用类型

java - 使用 GridBagLayout 将 JPanel 内的组件居中

java - 从方法返回 Double.NaN 是指示无效 double 值的好习惯

javascript - 正则表达式将字符串拆分为单独的键

Ruby =~ 与 === 运算符

string - 批处理 : Handle numbers above 2^32

java - 使用 UiBinder 创建登录面板。如何让用户登录并显示其他小部件