English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Patterning UNIX_LINES field in Java with example

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

Example1 

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 expressions start with MM-DD-YYY format accepts date
      String regex = "^T.";*e";
      //Create a Pattern object
      Pattern pattern = Pattern.compile(regex, Pattern.UNIX_LINES);
      //Create 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 result

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

In normal mode, \r is considered a carriage return.

Example2

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 expressions start with MM-DD-YYY format accepts date
      String regex = "^T.";*e";
      //Create a Pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create 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 result

This is the first line
Number of matches: 1