English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to use Java RegEx to match any character?

The meta-character "." matches any single character in Java regular expressions, it can be a letter, number, or any special character.

examples1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Read a string from the user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //The regular expression matches any character
      String regex = ".";
      //Compile the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieve the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count ++;
      }
      System.out.println("Given string contains ");+count+" characters.");
   }
}

Output Result

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

You can use the following regular expression to match any characters between a and b3A character-

a…b

Similarly, the expression “.*”matches with n characters.

examples2

The following Java program reads from the user5a string, and accept strings that start with b, end with a, and contain any number of characters in between.

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();
      }
      //Create a Pattern object
      Pattern p = Pattern.compile(regex);
      for(int i=0; i<5;i++) {
         //Create 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 Result

Enter 5 input strings:
barbara
boolean
baroda
ram
raju
barbara: accepted
boolean: not accepted
baroda: accepted
ram: not accepted
raju: not accepted