4

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Field.D
  • 158
  • 1
  • 1
  • 9

1 Answers1

4

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • thank you for replying, it works! however, can i put string list instead of that "word"? such as while((line = bufferedReader.readLine()) != null) { list.add("\\b(?:addAction|IntentFilter)\\b\\s*\\(\"\\s* line \\s*\"\\)"); } bufferedReader.close(); – Field.D Jun 06 '15 at 00:06
  • In most cases you can use that kind of alternation builder without any additional steps, just make sure there are no special characters, If there are any, you will need to escape the `line` with [`Pattern.quote`](http://stackoverflow.com/questions/15409296/what-is-the-use-of-pattern-quote-method). – Wiktor Stribiżew Jun 06 '15 at 07:59