What is the fastest way to check that a String contains only alphanumeric characters.
I've got some code that is going to chew up a lot of CPU and I wonder if there is going to be a quicker way than using pre-compiled regular expressions.
The idea is to use the regular expression ^[a-zA-Z0-9]*$ , which checks the string for alphanumeric characters. This can be done using the matches() method of the String class, which tells whether this string matches the given regular expression.
To check if String contains only alphabets in Java, call matches() method on the string object and pass the regular expression "[a-zA-Z]+" that matches only if the characters in the given string is alphabets (uppercase or lowercase).
*[^a-zA-Z0-9]. *$ tests for any character other than a-z, A-Z and 0-9. Thus if it finds any character other than these, it returns true(means non-alphanumeric character).
Use String.matches(), like:
String myString = "qwerty123456"; System.out.println(myString.matches("[A-Za-z0-9]+"));
That may not be the absolute "fastest" possible approach. But in general there's not much point in trying to compete with the people who write the language's "standard library" in terms of performance.
I've written the tests that compare using regular expressions (as per other answers) against not using regular expressions. Tests done on a quad core OSX10.8 machine running Java 1.6
Interestingly using regular expressions turns out to be about 5-10 times slower than manually iterating over a string. Furthermore the isAlphanumeric2()
function is marginally faster than isAlphanumeric()
. One supports the case where extended Unicode numbers are allowed, and the other is for when only standard ASCII numbers are allowed.
public class QuickTest extends TestCase { private final int reps = 1000000; public void testRegexp() { for(int i = 0; i < reps; i++) ("ab4r3rgf"+i).matches("[a-zA-Z0-9]"); } public void testIsAlphanumeric() { for(int i = 0; i < reps; i++) isAlphanumeric("ab4r3rgf"+i); } public void testIsAlphanumeric2() { for(int i = 0; i < reps; i++) isAlphanumeric2("ab4r3rgf"+i); } public boolean isAlphanumeric(String str) { for (int i=0; i<str.length(); i++) { char c = str.charAt(i); if (!Character.isLetterOrDigit(c)) return false; } return true; } public boolean isAlphanumeric2(String str) { for (int i=0; i<str.length(); i++) { char c = str.charAt(i); if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a) return false; } return true; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With