Posix character classes p{Alnum} Java regex


This class matches alpha numeric characters.

Example 

 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AlphanumericExample {
   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
      String regex = "[\p{Alnum}]";
      //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("Number of alphanumeric characters: "+count);
   }
}

Output 1

Enter a string
sample 123
Number of digits: 9

Output 2

Enter a string
@$#%&&#*
Number of alphanumeric characters: 0

Example 

 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      //Regular expression to match lower case letters
      String regex = "^\p{Alnum}+$";
      //Getting the input data
      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);
      System.out.println("Strings with only alphanumeric characters: ");
      for(int i=0; i<5;i++) {
         //Creating a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.matches()) {
            System.out.println(m.group());
         }
      }
   }
}

Output

Enter 5 input strings:
hello
1234
243test
##$$@
***
Strings with only alphanumeric characters:
hello
1234
243test

Updated on: 21-Feb-2020

406 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements