regex to check the string contains only letter and numbers but not only numbers

后端 未结 10 1449
温柔的废话
温柔的废话 2021-02-06 11:31

I need a help with regex which checks the string contains only letter and numbers but not only numbers

Valid

* letters
* 1wret
* 0123chars
* chars0123
*          


        
10条回答
  •  借酒劲吻你
    2021-02-06 11:54

    Here are the components of the regex we're going to use:

    • ^ and $ are the beginning and end of the string anchors respectively
    • \d matches a digit
    • [a-zA-Z] matches a letter
    • [a-zA-Z\d] matches a letter or a digit
    • * is "zero-or-more" repetition

    With these, we can now compose the regex we need (see on rubular.com):

    ^\d*[a-zA-Z][a-zA-Z\d]*$
    

    Here's an explanation of the pattern:

    from the beginning...  till the end
    |                      |
    ^\d*[a-zA-Z][a-zA-Z\d]*$
     \_/\______/\_________/
    

    The 3 parts are:

    • Maybe some digits as a prefix...
    • But then definitely a letter!
    • And then maybe some digits and letters as a suffix

    References

    • regular-expressions.info/Character Class, Anchors, and Repetition

提交回复
热议问题