如何使用正则表达式匹配多个单词 [英] How to use regex for matching multiple words
问题描述
如何使用正则表达式来匹配Java中的多个单词?例如,同时 addAction("word")
和 intentFilter("word")
进行匹配吗?
How can I use regex to match multiple words in java? For example, the addAction("word")
and intentFilter("word")
at the same time for matching?
我尝试过:
string REGEX ="[\\baddAction\\b|\\bintentFilter\\b]\\s*\([\"]\\s*\\bword\\b\\s*[\"]\)";
有人可以告诉我这种格式有什么问题,我该如何解决?
Could someone tell me what's wrong with this format and how can I fix it?
推荐答案
您正尝试使用替代在正则表达式中列出,但您使用的是字符类("[\\ baddAction \\ b | \\ bintentFilter \\ b]
).对于字符类,其中的所有字符都是单独匹配的,而不是给定的顺序.
You are trying to use alternative lists in a regex, but instead you are using a character class ("[\\baddAction\\b|\\bintentFilter\\b]
). With a character class, all characters in it are matched individually, not as a given sequence.
You learnt the word boundary, you need to also learn how grouping works.
您有一个结构:单词字符 + 带有双引号和括号的单词.
You have a structure: word characters + word in double quotes and parentheses.
因此,您需要将第一个分组,最好是使用非捕获组,并从 word
中删除一些单词边界(在指定的上下文中是多余的):
So, you need to group the first ones, and it is better done with a non-capturing group, and remove some word boundaries from the word
(it is redundant in the specified context):
String rgx ="\\b(?:addAction|intentFilter)\\b\\s*\\(\"\\s*word\\s*\"\\)";
System.out.println("addAction(\"word\")".matches(rgx));
System.out.println("intentFilter(\"word\")".matches(rgx));
true
true
这篇关于如何使用正则表达式匹配多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!