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

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 ...

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