Reputation: 9546
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
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 ]
Upvotes: 0
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