How to print all the characters of a string using regular expression in Java?

JavaObject Oriented ProgrammingProgramming

The meta character "." matches all the characters, to print all the characters using the regular expressions −

  • Compile the regular expression using the compile() method.

  • Create a Matcher object using the matcher() method.

  • Find the matches using the find() method and for every match print the matched contents (characters) using the group() method.

Example

 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      //Regular expression to match a string of non-word with length 2 to 6
      String regex = ".";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your input string: ");
      String input = sc.nextLine();
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher m = p.matcher(input);
      while(m.find()) {
         System.out.println(m.group());
      }
   }
}

Output

Enter your input string:
This is a sample text
T
h
i
s
i
s
a
s
a
m
p
l
e
t
e
x
t
raja
Published on 10-Jan-2020 16:27:19
Advertisements