
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Posix character classes p{Digit} Java regex
In this article, we will learn about the POSIX character classes p{Digit} Java regex. First, will know about \p{Digit} and the use of \p{Digit} along with examples.
What is \p{Digit}?
In Java regex, the \p{Digit} is a POSIX (Portable Operating System Interface) character class in Java regular expressions that matches any decimal digit character. This class matches decimal digits from 0 to 9.
The \p{Digit} is also equivalent to other expressions in Java:
- "\d": Follows the same POSIX standards.
- "[0-9]": For ASCII digits only.
How to Use \p{Digit} in Java?
We can use the \p{Digit} POSIX character in Java by declaring it in a string literal. In Java string literals, you need to escape the backslash with another backslash.
Below is the basic syntax for using \p{Digit} in Java regular expressions:
String regex = "[\p{Digit}]";
Example 1
Below is an example to count the number of digits present in a string using the \p{Digit} in Java1:
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DigitsExample { 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{Digit}]"; //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 digits: "+count); } }
Output
Enter a string sample text 22 37 48 84 Number of digits: 8 Enter a string Welcome to tutorilspoint Number of digits: 0
Example 2
Below is an example to print strings with only digits from a list of 5 strings using the \p{Digit} in Java:
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{Digit}+$"; //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 digits: "); 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 ##$$@ 222356 Strings with only digits: 1234 222356