Determine if string is all caps with regular expression

前端 未结 9 873
轻奢々
轻奢々 2020-12-30 00:46

How can you determine if a string is all caps with a regular expression. It can include punctuation and numbers, just no lower case letters.

相关标签:
9条回答
  • 2020-12-30 01:11
    $str="ABCcDEF";
    if ( preg_match ("/[a-z]/",$str ) ){
        echo "Lowercase found\n";
    }
    
    0 讨论(0)
  • 2020-12-30 01:17

    If you want to match the string against another regex after making sure that there are no lower case letters, you can use positive lookahead.

    ^(?=[^a-z]*$)MORE_REGEX$
    

    For example, to make sure that first and last characters are alpha-numeric:

    ^(?=[^a-z]*$)[A-Z0-9].*[A-Z0-9]$
    
    0 讨论(0)
  • 2020-12-30 01:22

    Basic:

    ^[^a-z]*$

    Exclude empty lines:

    ^[^a-z]+$

    Catering for exclusion of non-english chars (e.g. exclude a string containing à like 'VOILà'):

    ^\P{Ll}*$


    Expressions (e.g. JS):

    Single line:

    /^[^a-z]*$/

    Multi line:

    /^[^a-z]*$/m


    Theory:

    [a-z] matches a character that is a,b,c,...z

    [a-z]* matches a series of characters that are a,b,c,...z

    ^[a-z]* matches a series of characters that are not a,b,c...z

    ^[^a-z]*$ matches a string only containing a series of characters that are not a,b,c,...z from beginning to end.

    ^[^a-z]+$ ensures that there is at least one character that is not a,b,c,...z, and that the remaining characters are not a,b,c,...z in the string from beginning to end.

    ^\P{Ll}*$ matches all Unicode characters in the 'letter' group that have an uppercase variant - see https://www.regular-expressions.info/.

    0 讨论(0)
提交回复
热议问题