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 toon


Here we break down this regular expression and show what each element gives us:

\\s  Special regular expression character      matching a whitespace character. t  this matches the letter t. \\w*  Special regular expression character matching     zero or more word characters (non-whitespace). o this matches the leter o. \\w* Special regular expression character matching      zero or more word characters (non-whitespace).


This regular expression would not match the first word of the string even if it started with a t and contained an o. This is because the first piece of the regular expression matches on a whitespace character, and typically the string will not start with a whitespace character.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net