Java regex check non-alphanumeric string
The Alphanumericals are a combination of alphabetical [a-zA-Z]
and numerical [0-9]
characters, a total of 62 characters, and we can use regex [a-zA-Z0-9]+
to matches alphanumeric characters.
If we want regex matches non-alphanumeric
characters, prefix it with a negate symbol ^
, meaning we want any characters that are not alphanumeric.
^[^a-zA-Z0-9]+$
Regex explanation
^ # start string
[^a-zA-Z0-9] # NOT a-z, A-Z and 0-9
+ # one or more
$ # end string
1. Java regex non-alphanumeric
Below is a Java regex to check for non-alphanumeric characters.
StringNonAlphanumeric.java
package com.mkyong.regex.string;
public class StringNonAlphanumeric {
public static void main(String[] args) {
String str = "!@#$%";
if (str.matches("^[^a-zA-Z0-9]+$")) {
System.out.println("Yes, true.");
} else {
System.out.println("failed!");
}
}
}
Output
Terminal
Yes, true.
2. Java regex non-alphanumeric, underscore and colon
We can add all the invalid symbols into the bracket [ ]
.
^[^a-zA-Z0-9_:]+$
StringNonAlphanumericExtra.java
package com.mkyong.regex.string;
public class StringNonAlphanumericExtra {
public static void main(String[] args) {
String str = "!@#$%";
if (str.matches("^[^a-zA-Z0-9_:]+$")) {
System.out.println("Yes, true.");
} else {
System.out.println("failed!");
}
}
}
Output
Terminal
Yes, true.
For String str = "!@#_:";
, now it will display below:
Terminal
failed!
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-regex/string
References
About Author
Comments
Subscribe
0 Comments