regex for alphanumeric, but at least one character

后端 未结 6 1911
遇见更好的自我
遇见更好的自我 2020-11-27 18:21

In my asp.net page, I have an input box that has to have the following validation on it:

Must be alphanumeric, with at least 1 character (i.e. can\'t be ALL numbers)

6条回答
  •  死守一世寂寞
    2020-11-27 19:08

    ^[\p{L}\p{N}]*\p{L}[\p{L}\p{N}]*$
    

    Explanation:

    • [\p{L}\p{N}]* matches zero or more Unicode letters or numbers
    • \p{L} matches one letter
    • [\p{L}\p{N}]* matches zero or more Unicode letters or numbers
    • ^ and $ anchor the string, ensuring the regex matches the entire string. You may be able to omit these, depending on which regex matching function you call.

    Result: you can have any alphanumeric string except there's got to be a letter in there somewhere.

    \p{L} is similar to [A-Za-z] except it will include all letters from all alphabets, with or without accents and diacritical marks. It is much more inclusive, using a larger set of Unicode characters. If you don't want that flexibility substitute [A-Za-z]. A similar remark applies to \p{N} which could be replaced by [0-9] if you want to keep it simple. See the MSDN page on character classes for more information.

    The less fancy non-Unicode version would be

    ^[A-Za-z0-9]*[A-Za-z][A-Za-z0-9]*$
    

提交回复
热议问题