Matching Newlines in Text


String pattern = "\\d$"; String text =   "This is line 1\nHere is line 2\nThis is line 3\n";   Pattern regPat =    Pattern.compile(pattern, Pattern.MULTILINE); Matcher matcher = regPat.matcher(text); while (matcher.find()) {    System.out.println(matcher.group()); }



In this phrase, we use the Pattern.MULTILINE flag to match newlines in a text string. By default, the regular expression characters ^ and $ only match the beginning and end of an entire string. So, if a string contained multiple lines, distinguished with newline characters, the ^ expression would still only match the beginning of the string by default. If we pass the Pattern.MULTILINE flag to the Pattern.compile() method as we do in this phrase, the ^ will now match the first character following a line terminator, and the $ will match just before the line terminator. So, by using the Pattern.MULTILINE flag, the ^ would now match the start of every line in a string containing multiple lines separating by newline characters.

The output of this phrase will be

1 2 3


We use the pattern "\\d$". In this regular expression, the \\d matches any single digit. Because we are in MULTILINE mode, the $ matches just before a line terminator. So, the net effect is that our regular expression will match the single digit character contained at the end of any line. Thus, we get the output shown previously.




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