0

I have N keywords, key1 key2 ... keyN.

I have 3 pattern to match the keywords. (To make the problem simple I just use key1 instead of real keyword)

/keyword {keyword} (keyword)

I decide to find the match pattern by simply using regex:

The pattern I wrote:

(?:/)(key1|key2|key3)|(?:{)(key1|key2|key3)(?:})|(?:\()(key1|key2|key3)(?:\))

But for the keyword(key1|key2|key3), I need to write 3 times, also I got 3 groups (should be reduce to 1 for the best result).

How can I achieve this in Java or the standard regular expression ?

Gohan
  • 2,422
  • 2
  • 26
  • 45
  • Use string concatenation to build your regex. There is no better way in Java regex. – nhahtdh Jun 17 '15 at 08:43
  • possible duplicate of [Java Regex Multiple Pattern Group Replace](http://stackoverflow.com/questions/24815523/java-regex-multiple-pattern-group-replace) – Rajesh Jun 17 '15 at 08:51
  • possible duplicate of http://stackoverflow.com/questions/9723277/how-to-find-multiple-patterns-using-matcher-in-java – Rajesh Jun 17 '15 at 08:53

1 Answers1

0

It is possible (if I didn't miss any edge cases), but might be a bit cumbersome.

You can try this regex:

"([{/(])(aaa|bbb|ccc)((?<=/(aaa|bbb|ccc))|(?<=\\((aaa|bbb|ccc))\\)|(?<=\\{(aaa|bbb|ccc))\\})"
  • ([{/(]) matches /, (, {
  • (aaa|bbb|ccc) matches your key (group 2)
  • (?<=/(aaa|bbb|ccc)) matches nothing, but has a lookbehind that makes sure that / is at the beginning
    • (?<=\\((aaa|bbb|ccc))\\) matches ) and with the lookbehind makes sure that ( is at the beginning
    • (?<=\\{(aaa|bbb|ccc))\\} matches } and with the lookbehind makes sure that { is at the beginning

Using the information from this question: Backreferences in lookbehind you can try this regex without repitions:

"([{/(])(aaa|bbb|ccc)((?<=(?=/\\2).{1,4})|(?<=(?=\\(\\2).{1,4})\\)|(?<=(?=\\{\\2).{1,4})\\})"

where .{1,4} should be as long as needed to match your keys

Community
  • 1
  • 1
user140547
  • 7,750
  • 3
  • 28
  • 80
  • Your answer used the `key1|key2|key3` more than 3 times. I'll check your group trick – Gohan Jun 17 '15 at 09:39
  • Well unfortunately it is not possible to use backreferences in lookbehinds (at least in Java regex), so I am afraid there is no way to avoid that repition. But the match is always in group 2, so at least there are no if statements or so neceassary to retrieve the result – user140547 Jun 17 '15 at 10:01