How to match "= 3" with a border word in java?
I want to combine an independent word =3
, but the word boundary \b
doesn't work. How do I change the following java code?
Pattern pattern = Pattern.compile("\\b=3\\b");
String x = " =3 ";
System.out.println(pattern.matcher(x).replaceAll("something"));
Currently the above code cannot replace =3
withsomething
source to share
I was able to achieve this with the following regex:
(^\B=3\b|(\s)\B=3\b)
Forcing the insertion of a border before a character =
and ignoring other borders that create characters with \s
, and the case of starting a line with ^
.
So, to enter
=3 one =3 ==3 .=3 two =3a a=3
replacement "$2something"
will result in
"something one something ==3 .=3 two =3a a=3"
see in action here
$2
in a replacement value means keeping the value \s
in the original location and not breaking anything with the original string, but isolating the =3
instances.
source to share
I hope I'm not wrong, but I believe you can simply do the following:
Pattern pattern = Pattern.compile("\\B=3\\b");
I tested it and replaced it =3
=3
with something
, but there may be times when this does not work.
Please let me know if you need a specific use case and I'll see what I can do!
source to share