The next method is not as fast as the regular expression to implement, but it is one of the most efficient solutions (I think), because it uses bitwise operations, which are very fast.
My solution is harder and harder to read and maintain, but I think this is another easy way to do what you want.
A good way to verify that a string contains only numbers or capital letters is a simple 128 bits bitmask (2 Longs) representing an ASCII table.
So, for the standard ASCII table, there is 1 for every character that we want to save (bit from 48 to 57 and bit from 65 to 90)
So you can check that char is:
- Number with this mask:
0x3FF000000000000L (if character code <65) - Upper letter with this mask:
0x3FFFFFFL (if character code> = 65)
Thus, the following method should work:
public boolean validate(String aString) { for (int i = 0; i < aString.length(); i++) { char c = aString.charAt(i); if ((c <= 64) & ((0x3FF000000000000L & (1L << c)) == 0) | (c > 64) & ((0x3FFFFFFL & (1L << (c - 65))) == 0)) { return false; } } return true; }
Pier-alexandre bouchard
source share