How to match any character using Java RegEx

JavaObject Oriented ProgrammingProgramming

The meta character “.” in java regular expression matches any character (single) it could be the alphabet, number or, any special character.

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[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression to match any character
      String regex = ".";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count ++;
      }
      System.out.println("Given string contains "+count+" characters.");
   }
}

Output

Enter a String
hello how are you welcome to tutorialspoint
Given string contains 42 characters.

You can match any 3 characters between a and b using the following regular expression −

a…b

Similarly the expression “.*” matches n number of characters.

Example 2

Following Java program reads 5 strings from the user and accepts those which starts with b, ends with a with any number of characters in between them.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "^b.*a$";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         //Creating a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.find()) {
            System.out.println(input[i]+": accepted");
         } else {
            System.out.println(input[i]+": not accepted");
         }
      }
   }
}

Output

Enter 5 input strings:
barbara
boolean
baroda
ram
raju
barbara: accepted
boolean: not accepted
baroda: accepted
ram: not accepted
raju: not accepted
raja
Published on 19-Nov-2019 11:44:15
Advertisements