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

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.