Regular Expression "(re)" Sub-Expression in Java

JavaObject Oriented ProgrammingProgramming

The subexpression/metacharacter “( )” groups the regular expressions and remembers the matched text.

Example 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      String input = "Hello how are you welcome to Tutorialspoint";
      String regex = "H(ell|ow)";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

Output

Match found

Example 2

In the following example, we are trying to match a sentence with digits in it −

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternExample {
   public static void main(String[] args) {
      System.out.println("Enter input string: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression using groups
      String regex = "(?:.*)(\\d+)(.*)";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      boolean bool = matcher.matches();
      if(bool) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

Output

Enter input string:
This is a 5363 test string
Match found
raja
Published on 19-Nov-2019 14:23:17
Advertisements