regex for alphanumeric, but at least one character

后端 未结 6 1892
遇见更好的自我
遇见更好的自我 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:09

    Most answers to this question are correct, but there's an alternative, that (in some cases) offers more flexibility if you want to change the rules later on:

    ^(?=.*[a-zA-Z].*)([a-zA-Z0-9]+)$
    

    This will match any sequence of alphanumerical characters, but only if the first group also matches the whole sequence. It's a little-known trick in regular expressions that allows you to handle some very difficult validation problems.

    For example, say you need to add another constraint: the string should be between 6 and 12 characters long. The obvious solutions posted here wouldn't work, but using the look-ahead trick, the regex simply becomes:

    ^(?=.*[a-zA-Z].*)([a-zA-Z0-9]{6,12})$
    

提交回复
热议问题