views:

178

answers:

3

I want to be able to test if a powershell string is all lowercase letters.

I am not the worlds best regex monkey, but I have been trying along these lines:

if( $mystring -match "[a-z]^[A-Z]" ) {
echo "its lower!"
}

But of course they doesn't work, and searching the interwebs hasn't got me anywhere. Does anyone know the way to do this (besides testing every character in a loop)?

+5  A: 

PowerShell by default matches case-insensitively, so you need to use the -cmatch operator:

if ($mystring -cmatch "^[a-z]*$") { ... }

-cmatch is always case-sensitive, while -imatch is always case-insensitive.

Side note: Your regular expression was also a little weird. Basically you want the one I provided here which consists of

  • The anchor for the start of the string (^)
  • A character class of lower-case Latin letters ([a-z])
  • A quantifier, telling to repeat the character class at least 0 times, thereby matching as many characters as needed (*). You can use + instead to disallow an empty string.
  • The anchor for the end of the string ($). The two anchors make sure that the regular expression has to match every character in the string. If you'd just use [a-z]* then this would match any string that has a string of at least 0 lower-case letters somewhere in it. Which would be every string.

P.S.: Ahmad has a point, though, that if your string might consist of other things than letters too and you want to make sure that every letter in it is lower-case, instead of also requiring that the string consists solely of letters, then you have to invert the character class, sort of:

if ($mystring -cmatch "^[^A-Z]*$") { ... }

The ^ at the start of the character class inverts the class, matching every character not included. Thereby this regular expression would only fail if the string contains upper-case letters somewhere. Still, the -cmatch is still needed.

Joey
that works great, thanks for the extra explanation.
falkaholic
A: 

Try this pattern, which matches anything that is not an uppercase letter: "^[^A-Z]*$"

This would return false for any uppercase letters while allowing the string to contain other items as long as all letters are lowercase. For example, "hello world 123" would be valid.

If you strictly want letters without spaces, numbers etc., then Johannes's solution fits.

Ahmad Mageed
PowerShell matches case-insensitively by default, thereby this can't work. Not without another operator.
Joey
+1  A: 

If your test is so simple, you can and probably should avoid the use of regular expressions:

$mystring -ceq $mystring.ToLower()
guillermooo
wow, that is simpler. Next time I am using that.
falkaholic
Make sure to use the method's overloaded signature accepting a `CultureInfo` object if you need too.
guillermooo