imeluntuk
imeluntuk

Reputation: 395

Why "|" (or) in regex give weird result when used as replacement criteria

First of all, I'm not an expert at regex. So please take a look at this regex :

([km]u|nya|[kl]ah|pun)$

I want to remove "nya" and "lah" in following string :

diserahkannyalah

Rather than show "diserahkan", its result is "diserahkannya". So, not all criteria satisfied when attempting replace operation. Why is it happen? Im using Java and use replaceAll method from Matcher

Upvotes: 1

Views: 56

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

You just need to add a quantifier:

([km]u|nya|[kl]ah|pun)+$
                      ^

See the regex demo

This + tells the regex engine to repeat matching the pattern the + quantifies 1 or more times. Here, the quantifier appears after a ) that closes a capturing group, so, the whole capturing group pattern is quantified.

Note that if you are just removing all these substrings, you can make use of a non-capturing group: (?:[km]u|nya|[kl]ah|pun)+$.

See the Quantifier Cheat Sheet for more details on regex quantifiers.

Upvotes: 1

Related Questions