如何使用正则表达式匹配多个单词

How to use regex for matching multiple words

如何使用正则表达式匹配 java 中的多个单词?比如addAction("word")intentFilter("word")同时匹配?

我试过了:

string REGEX ="[\baddAction\b|\bintentFilter\b]\s*\([\"]\s*\bword\b\s*[\"]\)";

谁能告诉我这种格式有什么问题,我该如何解决?

您正在尝试使用 alternative lists in a regex, but instead you are using a character class ("[\baddAction\b|\bintentFilter\b])。对于一个字符class,其中的所有字符都是单独匹配的,而不是作为一个给定的序列。

您学习了 word boundary, you need to also learn how grouping 作品。

你有一个结构:单词字符 + 双引号和括号中的单词

因此,您需要对第一个进行分组,最好使用非捕获组来完成,并从 word 中删除一些单词边界(在指定的上下文中是多余的):

String rgx ="\b(?:addAction|intentFilter)\b\s*\(\"\s*word\s*\"\)";
System.out.println("addAction(\"word\")".matches(rgx));
System.out.println("intentFilter(\"word\")".matches(rgx));

the demo

的输出
true
true