Skip to content

Java RegEx – Match Word Boundary

Java RegEx – Match Word Boundary example shows how to match a word boundary in Java regular expression. The example also shows how to use the word boundary matcher \b properly.

How to match a word boundary in Java regular expressions?

Let’s first see an example of why it is so important to learn boundary matching in regex. The below-given code tries to find the word “at” in the source string.

Output

As you can see from the output, what we wanted to do was to search the word “at” in the source string. The code not only found the exact word “at” in the string, but it also matched the substring “at” inside the word “cat” and others (partial matches).

In order to find the exact match and ignore all the partial matches, we need to use the word boundaries. In regex, it is denoted by “\b”. By using the “\b” on both sides of the pattern, we can get rid of the matches inside other words as given below.

Output

As you can see from the output, the code worked as intended this time and found the exact word we were looking for.

The regex “\b” is essentially a zero-width assertion. It matches at the start of the string, at the end of the string, and in between two characters where one character is a word character (i.e. \w in regex) and the other is not (i.e. \W in regex).

Visit Java regex tutorial to learn more about regex.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.