
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{ASCII} Java regex.
In this article, we will learn about the p{ASCII} of the POSIX character class in Java regex.
What is \p{ASCII}?
In Java regex, \p{ASCII} POSIX character class matches any of the characters that fall within ASCII. ASCII (American Standard Code for Information Interchange) defines a character encoding standard consisting of 128 characters (0-127). This class matches the ASCII characters within the range of \x00-\x7F.
Printable characters in the \p{ASCII} of the Java Regex are:
- Numbers (0 to 9)
- Uppercase letters (A to Z)
- Lowercase letters (a to z)
- Punctuation and Symbols
How to Use \p{ASCII} in Java?
We can use the \p{ASCII} 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{ASCII} in Java regular expressions:
String regex = "[^\p{ASCII}]";
Using \p{ASCII} Counting Non-ASCII Characters in a String
Below, we have declared a class named "Example" in which we will print a message asking for input, create a string scanner, and store the string in a variable called "input".
Then we declared a string literal named "regex" to store the \p{ASCII} POSIX character. Compiles the regular expression into a Pattern object, and then we will create a Matcher object that will apply the pattern to the input string.
We will use a count variable to store the number of non-ASCII characters, and the find() method looks for the next match in the input string and increments the count if a non-ASCII character is found, and lastly prints the number of non-ASCII characters in the given string.
Example of Posix Character Classes p{ASCII} in Java Regex
Below is an example of \p{ASCII} in Java to count the non-ASCII characters in a user-defined string:
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 String regex = "[^\p{ASCII}]"; //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 non-ASCII characters in the given string: "+count); } }
Output
Enter a string why do we fall Number of non-ASCII characters in the given string: 0