Regular Expression re+ Metacharacter in Java

JavaObject Oriented ProgrammingProgramming

The subexpression/metacharacter “re+” matches one or more occurrences of the preceding expression.

Example 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "aabc+";
      String input = "aabcabcaabcabbcaabcbcaabc";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}

Output

Number of matches: 4

Example 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main( String args[] ) {
      String regex = "[0-9]+";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an input string: ");
      String input = sc.nextLine();
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher m = p.matcher(input);
      if(m.find()) {
         System.out.println("Given input contains digits");
      } else {
         System.out.println("Given input doesn't contain digits");
      }
   }
}

Output 1

Enter an input string:
sample text
Given input doesn't contain digits

Output 2

Enter an input string:
sample data 464
Given input contains digits
raja
Published on 19-Nov-2019 10:57:24
Advertisements