Santanu Sahoo
Santanu Sahoo

Reputation: 1157

Regex non-Word boundary and spaces

I am looking for a single regex that will match any sentence that contains a "new" word then "ee" non-word boundary in it. Below is the code where anything I put before or after non-word boundary returns False.

String sa = "this is new freeCode ";
System.out.println(sa.matches(".*\\s\\bnew\\b\\sfre.*")); //True
System.out.println(sa.matches(".*\\s\\Bee\\B\\s.*"));     //False
System.out.println(sa.matches(".*\\Bee\\B.*"));           //True

Upvotes: 2

Views: 585

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

Here is the explanation why these tests yield these results:

System.out.println(sa.matches(".*\\s\\bnew\\b\\sfre.*")); //True

this is new freeCode contains something+whitespace+word boundary + new + word boundary + whitespace+fre+something. Word boundary matches inbetween n and w f.

System.out.println(sa.matches(".*\\s\\Bee\\B\\s.*")); //False

Non-word boundary \B between \s and e cannot match since e is a word character. Thus, no match.

System.out.println(sa.matches(".*\\Bee\\B.*")); //True

Non-word boundary \B matches between e since e in freecode is in not at a word boundary position (it is between 2 letters, word characters), and the final e is followed again by a letter (c in this case). This is a valid match.

To enable both checks, you need to combine the first and third regex patterns. You do not need both \s\b and \b\s. If you want to just match a whole word new remove \s:

System.out.println(sa.matches(".*\\bnew\\b.*\\Bee\\B.*"));

If you need to match spaces around new, use:

System.out.println(sa.matches(".*\\snew\\s.*\\Bee\\B.*"));

Upvotes: 1

vks
vks

Reputation: 67968

^.*?\\bnew\\s\\S*\\Bee\\B.*$

You can try this.See demo.

https://regex101.com/r/cK4iV0/19

This will match the word new and then ee without word boundary on either side.

Upvotes: 1

Related Questions