O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Finding All Occurrences of a Pattern

String pattern = "\\st(\\w)*o(\\w)*";
											Pattern regPat = Pattern.compile(pattern);
											String text =
											"The words are town tom ton toon house.";
											Matcher matcher = regPat.matcher(text);
											while (matcher.find()) {
											String matchedText = matcher.group();
											System.out.println("match - " + matchedText);
											}

In the previous phrases in this chapter, we found a single match of a pattern. In this phrase, we find all the occurrences of a given match pattern that occurs within a string. The pattern we use for this phrase is "\\st(\\w)*o(\\w)*". This regular expression will find any words that begin with t and contain the letter o in them. The output printed from our System.out.println()statements will be the following:

town tom ton ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required