Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Make sure a String contains only alphanumeric, spaces and dashes

In Java, I need to make sure a String only contains alphanumeric, space and dash characters.

I found the class org.apache.commons.lang.StringUtils and the almost adequate method isAlphanumericSpace(String)... but I also need to include dashes.

What is the best way to do this? I don't want to use Regular Expressions.

like image 544
Lancelot Avatar asked Apr 14 '09 23:04

Lancelot


2 Answers

You could use:

StringUtils.isAlphanumericSpace(string.replace('-', ' '));
like image 63
Skip Head Avatar answered Nov 15 '22 09:11

Skip Head


Hum... just program it yourself using String.chatAt(int), it's pretty easy...

Iterate through all char in the string using a position index, then compare it using the fact that ASCII characters 0 to 9, a to z and A to Z use consecutive codes, so you only need to check that character x numerically verifies one of the conditions:

  • between '0' and '9'
  • between 'a' and 'z'
  • between 'A and 'Z'
  • a space ' '
  • a hyphen '-'

Here is a basic code sample (using CharSequence, which lets you pass a String but also a StringBuilder as arg):

public boolean isValidChar(CharSequence seq) {
    int len = seq.length();
    for(int i=0;i<len;i++) {
        char c = seq.charAt(i);
        // Test for all positive cases
        if('0'<=c && c<='9') continue;
        if('a'<=c && c<='z') continue;
        if('A'<=c && c<='Z') continue;
        if(c==' ') continue;
        if(c=='-') continue;
        // ... insert more positive character tests here
        // If we get here, we had an invalid char, fail right away
        return false;
    }
    // All seen chars were valid, succeed
    return true;
}
like image 36
Varkhan Avatar answered Nov 15 '22 07:11

Varkhan