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

后端 未结 10 1446
温柔的废话
温柔的废话 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:50
    ^[0-9]*[a-zA-Z]+[0-9a-zA-Z]*$
    

    translated: from the beginning, match 0 or more numbers, then match at least one letter, then match zero or more letters or numbers until the end.

    0 讨论(0)
  • 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
    0 讨论(0)
  • 2021-02-06 11:56

    Instead of using a regular expression, you can also use the ctype_*() functions:

    var_dump(ctype_alnum('letters') && !ctype_digit('letters'));     // bool(true)
    var_dump(ctype_alnum('0123chars') && !ctype_digit('0123chars')); // bool(true)
    var_dump(ctype_alnum('1324') && !ctype_digit('1324'));           // bool(false)
    var_dump(ctype_alnum('xcvxxc%$#') && !ctype_digit('xcvxxc%$#')); // bool(false)
    

    But if you want a regular expression, you can use this:

    var_dump(preg_match('/^[a-z0-9]*[a-z]+[a-z0-9]*$/i', $input));
    
    0 讨论(0)
  • 2021-02-06 11:57

    This should do it:

    ^[0-9]*[a-zA-Z]+[a-zA-Z0-9]*$
    

    This requires at least one character of [a-zA-Z].

    0 讨论(0)
  • 2021-02-06 11:58
    [a-z0-9]*[a-z]+[a-z0-9]*
    
    0 讨论(0)
  • 2021-02-06 12:00

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

    • (?=.*[a-z]) positive lookahead to make sure that there is at least one letter in the string (but doesn't consume any characters - gives up the matched characters as soon as it returns (in this case, as soon as it finds a letter)).
    • [a-zA-Z0-9]+ make sure string contains only alphanumeric characters.
    • ^ and $ are start and end of string delimiters.
    0 讨论(0)
提交回复
热议问题