Java word boundary starts ends with
In Java, you can use word boundaries to match patterns that occur at the start or end of a word. Word boundaries are represented by the \b
character sequence in regular expressions.
Here are some examples of how to use word boundaries to match patterns that occur at the start or end of a word in Java:
- Match a word that starts with "foo":
String regex = "\\bfoo\\w*\\b"; String input = "foo bar baz"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { System.out.println(matcher.group()); } // Output: fooSecruo:www.theitroad.com
- Match a word that ends with "bar":
String regex = "\\b\\w*bar\\b"; String input = "foo bar baz"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { System.out.println(matcher.group()); } // Output: bar
- Match a word that starts with "foo" and ends with "bar":
String regex = "\\bfoo\\w*bar\\b"; String input = "foo bar baz"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { System.out.println(matcher.group()); } // Output: foo bar
In the examples above, the \b
character sequence matches the word boundary at the start or end of a word, and \w*
matches any sequence of word characters.