Matching multiple lines in Java regular expressions


To match/search a input data with multiple lines −

  • Get the input string.

  • Split it into an array of tokens by passing "\r?\n" as parameter to the split method.

  • Compile the required regular expression using the compile() method of the pattern class.

  • Retrieve the matcher object using the matcher() method.

  • In the for loop find matches in the each element (new line) of the array using the find() method.

  • Reset the input of the matcher to the next element of the array using the reset() method.

Example

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchingText{
   public static void main(String[] args) {
      String input = "sample text line 1 \n line2 353 35 63 \n line 3 53 35";
      String regex = "\d";
      String[] strArray = input.split("\r?\n");
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      for (int i = 0; i < strArray.length; i++) {
         matcher.reset(strArray[i]);
         System.out.println("Line:: "+(i+1));
         while (matcher.find()) {
            System.out.print(matcher.group()+" ");
         }
      System.out.println();
      }
   }
}

Output

Line:: 1
1
Line:: 2
2 3 5 3 3 5 6 3
Line:: 3
3 5 3 3 5

Updated on: 13-Jan-2020

581 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements