Kong
Kong

Reputation: 9546

Regex that matches only one occurrence

I'm wanting to replace all occurrences of "=" with "==" in a string with a Regex, but only where there is a single occurrence of "=".

Basically I want to transform:

where a = b | c == d

into

where a == b | c == d

What I'm struggling with is finding just the one occurrence. I've tried [^=]=[^=], but that is matching the characters on either side too.

Upvotes: 2

Views: 4027

Answers (3)

progrenhard
progrenhard

Reputation: 2363

[^=](=)[^=]

Regular expression visualization

Edit live on Debuggex

Just use capture groups and select them that way.

Upvotes: 1

Travis J
Travis J

Reputation: 82267

Just use the case where there is a space on both sides. " = " becomes " == "

String str = input.replace(" = ", " == ");

Edit

If you are looking for situations where a=6 is present and want to make it a==6 and you cannot take advantage of targeting the spaces, you may try

[\w ](=)[\w ]

Regular expression visualization

Edit live on Debuggex

Upvotes: 0

arshajii
arshajii

Reputation: 129497

You can try using lookarounds:

(?<!=)=(?!=)

Using your example:

System.out.println("where a = b | c == d".replaceAll("(?<!=)=(?!=)", "=="));
where a == b | c == d

Upvotes: 4

Related Questions