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 ?

3

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Your answer used the key1|key2|key3 more than 3 times. I'll check your group trick
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.