Regex to match lines containing multiple strings in Java

Java 8Object Oriented ProgrammingProgramming

Example

Live Demo

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SearchRegex {
   private Pattern subPattern = Pattern.compile(SUBJECT_PATTERN);
   private Matcher matcher;
   private static final String SUBJECT_PATTERN = "(?s)Subject 1:\\s(.*)Subject 2:";

   public static void main(String[] args) {
      String d = "Subject 1: Java\n" + "Subject 2: Python";
      SearchRegex obj = new SearchRegex();
      List list = obj.getSubject(d);
      System.out.println("Address Result : " + list);
   }
   private List getSubject(String d){
      List result = new ArrayList();
      matcher = subPattern.matcher(d);

      while (matcher.find()) {
         result.add(matcher.group(1));
      }
      return result;
   }
}

Output

Address Result : [Java]
raja
Published on 04-May-2018 08:22:37
Advertisements