Pattern MULTILINE field in Java with examples

JavaObject Oriented ProgrammingProgramming

Enables multiline mode.

In general, the ^ and $ meta characters matches the start and end of the given input with the specified characters irrespective of the number of lines in it.

Example 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MULTILINE_Example {
   public static void main( String args[] ) {
      //String regex = "(^This)";//.*t$)";
      String input = "2234 This is a sample text\n"
         + "1424 This second 2335 line\n"
         + "This id third 455 line\n"
         + "Welcome to Tutorialspoint\n";
      Pattern pattern = Pattern.compile("^([0-9]+).*");//, Pattern.MULTILINE);
      Matcher matcher = pattern.matcher(input);
      while(matcher.find()) {
         System.out.println(matcher.group(1));
      }
   }
}

Output

2234

When you use this as flag value to the compile() method, the whole inputs sequence will be treated as a single line and the meta characters ^ and $ matches the beginning and end of the given input sequence.

Example 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MULTILINE_Example {
   public static void main( String args[] ) {
      //String regex = "(^This)";//.*t$)";
      String input = "2234 This is a sample text\n"
         + "1424 This second 2335 line\n"
         + "This id third 455 line\n"
         + "Welcome to Tutorialspoint\n";
      Pattern pattern = Pattern.compile("^([0-9]+).*", Pattern.MULTILINE);
      Matcher matcher = pattern.matcher(input);
      while(matcher.find()) {
         System.out.println(matcher.group(1));
      }
   }
}

Output

2234
1424
raja
Published on 20-Nov-2019 06:13:21
Advertisements