Ming Ming - 5 months ago 18
Java Question

how to match "=3" with word boundary in java?

I want to match an independent word of "=3", but the word boundary "\b" doesn't work. How do I modify the following java code?

Pattern pattern = Pattern.compile("\\b=3\\b");
String x = " =3 ";

Currently, the code cannot replace the =3 with something.

Answer Source

I was able to achieve this with the following regex;


Forcing it to insert a boundary before = sign, and ignoring other boundary creating chars with a \s, and also a case for the beginning of the line captures with ^.

So for an input

=3 one =3 ==3 .=3 two =3a a=3

replacement with "$2something" will result

"something one something ==3 .=3 two =3a a=3"

see it in action here

$2 in the replacement value is to keep \s space value in its original location, and not to break anything with the original string but isolated =3 instances.