Regular Expression for alphanumeric and underscores

前端 未结 20 758
北荒
北荒 2020-11-22 10:01

I would like to have a regular expression that checks if a string contains only upper and lowercase letters, numbers, and underscores.

相关标签:
20条回答
  • 2020-11-22 10:35

    To check the entire string and not allow empty strings, try

    ^[A-Za-z0-9_]+$
    
    0 讨论(0)
  • 2020-11-22 10:36

    use lookaheads to do the "at least one" stuff. Trust me it's much easier.

    Here's an example that would require 1-10 characters, containing at least one digit and one letter:

    ^(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9]{1,10}$
    

    NOTE: could have used \w but then ECMA/Unicode considerations come into play increasing the character coverage of the \w "word character".

    0 讨论(0)
  • 2020-11-22 10:37

    I believe you are not taking Latin and Unicode characters in your matches. For example, if you need to take "ã" or "ü" chars, the use of "\w" won't work.

    You can, alternatively, use this approach:

    ^[A-ZÀ-Ýa-zà-ý0-9_]+$
    

    Hope it helps!

    0 讨论(0)
  • 2020-11-22 10:39

    The following regex matches alphanumeric characters and underscore:

    ^[a-zA-Z0-9_]+$
    

    For example, in Perl:

    #!/usr/bin/perl -w
    
    my $arg1 = $ARGV[0];
    
    # check that the string contains *only* one or more alphanumeric chars or underscores
    if ($arg1 !~ /^[a-zA-Z0-9_]+$/) {
      print "Failed.\n";
    } else {
        print "Success.\n";
    }
    
    0 讨论(0)
  • 2020-11-22 10:40

    How about:

    ^([A-Za-z]|[0-9]|_)+$
    

    ...if you want to be explicit, or:

    ^\w+$
    

    ...if you prefer concise (Perl syntax).

    0 讨论(0)
  • 2020-11-22 10:42

    This should work in most of the cases.

    /^[\d]*[a-z_][a-z\d_]*$/gi

    And by most I mean,

    abcd       True
    abcd12     True
    ab12cd     True
    12abcd     True
    
    1234       False
    


    Explanation

    1. ^ ... $ - match the pattern starting and ending with
    2. [\d]* - match zero or more digits
    3. [a-z_] - match an alphabet or underscore
    4. [a-z\d_]* - match an alphabet or digit or underscore
    5. /gi - match globally across the string and case-insensitive
    0 讨论(0)
提交回复
热议问题