tags:

views:

137

answers:

8

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.

+1  A: 

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

ItzWarty
How do you use that, for example, to extract all satisfactory lines with a `grep`?
Alex Martelli
+1  A: 

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.

Mark E
+2  A: 

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

Jerry Coffin
This will only match strings of exactly one character in length.
Tim Pietzcker
@Tim:Oops. Thanks -- fixed that.
Jerry Coffin
+1  A: 

Simplest would seem to be:

^[^a-z]*$
Alex Martelli
+5  A: 
m/^[^a-z]*$/

For non-English characters,

m/^[^\p{Ll}]*$/
KennyTM
+1 for a culture-agnostic solution.
Adam Maras
A: 

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

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

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