Regular expression - starting and ending with a letter, accepting only letters, numbers and _

后端 未结 4 1164
名媛妹妹
名媛妹妹 2020-12-14 17:12

I\'m trying to write a regular expression which specifies that text should start with a letter, every character should be a letter, number or underscore, there should not be

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 17:51

    I'll take a stab at it:

    /^[a-z](?:_?[a-z0-9]+)*$/i
    

    Explained:

    /
     ^           # match beginning of string
     [a-z]       # match a letter for the first char
     (?:         # start non-capture group
       _?          # match 0 or 1 '_'
       [a-z0-9]+   # match a letter or number, 1 or more times
     )*          # end non-capture group, match whole group 0 or more times
     $           # match end of string
    /i           # case insensitive flag
    

    The non-capture group takes care of a) not allowing two _'s (it forces at least one letter or number per group) and b) only allowing the last char to be a letter or number.

    Some test strings:

    "a": match
    "_": fail
    "zz": match
    "a0": match
    "A_": fail
    "a0_b": match
    "a__b": fail
    "a_1_c": match
    

提交回复
热议问题