How to find a whole word in a String in java

The Solution to How to find a whole word in a String in java is

The example below is based on your comments. It uses a List of keywords, which will be searched in a given String using word boundaries. It uses StringUtils from Apache Commons Lang to build the regular expression and print the matched groups.

String text = "I will come and meet you at the woods 123woods and all the woods";

List<String> tokens = new ArrayList<String>();

String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);

while (matcher.find()) {

If you are looking for more performance, you could have a look at StringSearch: high-performance pattern matching algorithms in Java.

~ Answered on 2011-02-23 12:50:43

Most Viewed Questions: