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

+3


source to share


4 answers


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.

+3


source


Use this:

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

      



Note \B

instead of \B

at the beginning.

+2


source


Lookbehind seems to work

        String x = " 8=3 =3 a=3 =3d =3 =3";
        x = x.replaceAll("(?<!\\b)=3\\b", "something");
        System.out.println(x);

      

Output

8 = 3 something a = 3 = 3d something something

+2


source


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!

+1


source







All Articles