Pattern UNIX Lines Field in Java with Examples



This flag enables Unix lines mode. In the Unix lines mode, only '\n' is used as a line terminator and ?\r' is treated as a literal character.


Example 1

Open Compiler
import java.util.regex.Matcher; import java.util.regex.Pattern; public class LTERAL_Example { public static void main(String[] args) { String input = "This is the first line\r" + "This is the second line\r" + "This is the third line\r"; //Regular expression to accept date in MM-DD-YYY format String regex = "^T.*e"; //Creating a Pattern object Pattern pattern = Pattern.compile(regex, Pattern.UNIX_LINES); //Creating a Matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; System.out.println(matcher.group()); } System.out.println("Number of matches: "+count); } }

Output

This is the first line
This is the second line
This is the third line
Number of matches: 1

Whereas in normal mode \r is treated as carriage-return.

Example 2

Open Compiler
import java.util.regex.Matcher; import java.util.regex.Pattern; public class LTERAL_Example { public static void main(String[] args) { String input = "This is the first line\r" + "This is the second line\r" + "This is the third line\r"; //Regular expression to accept date in MM-DD-YYY format String regex = "^T.*e"; //Creating a Pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; System.out.println(matcher.group()); } System.out.println("Number of matches: "+count); } }

Output

This is the first line
Number of matches: 1
Updated on: 2024-08-08T12:56:52+05:30

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements