Java regex - exclude newline from word boundary

79 views Asked by At

I'm trying to come up with a Java regex which matches a word even when there is a \n in the input text. Kindly note that \n is supposed to appear as raw string. I am using the typical word boundary \bHelloWorld\b - https://regex101.com/r/Se5iVW/1 .

For example,

HelloWorld is a beautiful word \nHelloWorld\nHelloWorld\nHelloWorld hello noHelloWorld \n HelloWorldno noHelloWorld  HelloWorldno \nnoHelloWorld \nHelloWorld ...

In this, I expect 5 matches (first four HelloWorld and last one).

1

There are 1 answers

5
anubhava On

You may use this regex with a positive lookbehind that matches \b or literal \n in alternations:

(?<=\\n|\b)HelloWorld\b

RegEx Demo