regexpowershellcase

Check string for all lowercase letters in PowerShell


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 Internet hasn't got me anywhere. Is there a way to do this (besides testing every character in a loop)?


Solution

  • 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

    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.