check if string contains only alpha numeric characters

Discussion in 'Java' started by angelochen960, Aug 19, 2008.

  1. hi,

    I need to check if a string contains only alpha numeric characters, no
    space, no other special characters, looks i need a regular expression,
    but too poor in this area, any idea how to do this? thanks.

    Angelo
     
    angelochen960, Aug 19, 2008
    #1
    1. Advertisements

  2. angelochen960

    Arne Vajhøj Guest

    Try:

    private static Pattern p = Pattern.compile("^[A-Za-z0-9]+$");
    private static boolean match(String s) {
    return p.matcher(s).matches();
    }

    Arne
     
    Arne Vajhøj, Aug 19, 2008
    #2
    1. Advertisements

  3. angelochen960

    Stefan Ram Guest

    public class Main
    { public static void main( final java.lang.String[] args )
    { java.lang.System.out.println( "abc123".matches( "\\p{Alnum}*" ));
    java.lang.System.out.println( "abc,23".matches( "\\p{Alnum}*" ));
    java.lang.System.out.println( ",bc123".matches( "\\p{Alnum}*" ));
    java.lang.System.out.println( "abc12,".matches( "\\p{Alnum}*" )); }}

    true
    false
    false
    false
     
    Stefan Ram, Aug 19, 2008
    #3
  4. this works, thanks.
     
    angelochen960, Aug 19, 2008
    #4
  5. angelochen960

    Roedy Green Guest

    The following is part of the StringTools class.
    http://mindprod.com/products1.html#COMMON11

    /**
    * Ensure the string contains only legal characters.
    *
    * @param candidate string to test.
    * @param legalChars characters than are legal for candidate.
    * @return true if candidate is formed only of chars from the
    legal set.
    */
    public static boolean isLegal( String candidate, String legalChars
    )
    {
    for ( int i = 0; i < candidate.length(); i++ )
    {
    if ( legalChars.indexOf( candidate.charAt( i ) ) < 0 )
    {
    return false;
    }
    }
    return true;
    }

    ..
    legalChars would be
    "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
     
    Roedy Green, Aug 19, 2008
    #5
  6. <code>
    private static Pattern p = Pattern.compile("[^A-Za-z0-9]");
    private static boolean match(String s) {
    return ! p.matcher(s).find();
    }
    </code>

    Might be quicker.

    -.-

    The least overhead would be with:

    <code>
    public static boolean checkString(String s){
    for(int ii = s.length(); ii --> 0; ){
    if( ! Character.isLetterOrDigit(s.charAt(ii)) )
    return false;
    }

    return true;
    }
    </code>

    Though I18N might be an issue.
     
    Daniele Futtorovic, Aug 19, 2008
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.