How to use regex for matching multiple words

拜拜、爱过 提交于 2021-02-16 18:13:19

问题


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?

I tried:

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?


回答1:


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.

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));

Output of the demo

true
true


来源:https://stackoverflow.com/questions/30677259/how-to-use-regex-for-matching-multiple-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!