Brian
Brian

Reputation: 27392

Determine if string is all caps with regular expression

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.

Upvotes: 32

Views: 33475

Answers (9)

kennytm
kennytm

Reputation: 523534

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

For non-English characters,

m/^\P{Ll}*$/

(\P{Ll} is the same as [^\p{Ll}], which accepts all characters except the ones marked as lower-case.)

Upvotes: 29

Dan
Dan

Reputation: 3020

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/.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490408

That sounds like you want: ^[^a-z]*$

Upvotes: 11

Amarghosh
Amarghosh

Reputation: 59461

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]$

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342679

$str="ABCcDEF";
if ( preg_match ("/[a-z]/",$str ) ){
    echo "Lowercase found\n";
}

Upvotes: 0

me2
me2

Reputation: 3119

How about (s == uppercase(s)) --> string is all caps?

Upvotes: -1

Alex Martelli
Alex Martelli

Reputation: 882231

Simplest would seem to be:

^[^a-z]*$

Upvotes: 1

Mark Elliot
Mark Elliot

Reputation: 77074

The string contains a lowercase letter if the expression /[a-z]/ returns true, so simply perform this check, if it's false you have no lowercase letters.

Upvotes: 1

Warty
Warty

Reputation: 7405

Why not just use if(string.toUpperCase() == string)? ._. Its more "elegant"...
I think you're trying to force in RegExp, but as someone else stated, I don't think this is the best use of regexp...

Upvotes: 5

Related Questions