Why does wordCount end up being 1, rather than 5, in the code below?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordCount {
public static void main(String[] args) {
final Pattern wordCountRegularExpression = Pattern.compile("\\S+");
final Matcher matcher = wordCountRegularExpression
.matcher("one two three four five");
int wordCount = 0;
while (matcher.find()) {
wordCount++;
}
System.out.println("wordCount: " + wordCount);
}
}
Doesn’t the pattern “\S+” match a word, since it means one or more non-space characters?
This does work by the way:
final Pattern wordCountRegularExpression = Pattern.compile("\\b\\w+\\b");
But I still don’t understand why the original code doesn’t work.
Yes.