在PowerShell中检查所有小写字母的字符串 [英] Check string for all lowercase letters in PowerShell

查看:193
本文介绍了在PowerShell中检查所有小写字母的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够测试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)?

推荐答案

PowerShell默认情况下不区分大小写匹配,因此您需要使用-cmatch运算符:

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

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

-cmatch总是 区分大小写,而-imatch总是不区分大小写.

-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

  • ,用于字符串的开头( ^)
  • 由小写拉丁字母组成的 字符类 ([a-z])
  • 一个 量化器 ,要求重复字符类至少0次,从而匹配所需的尽可能多的字符(*).您可以改用+禁止使用空字符串.
  • ,用于字符串的结尾( $).这两个锚确保正则表达式必须匹配字符串中的每个字符.如果只使用[a-z]*,则它将匹配其中包含至少0小写字母 somewhere 的任何字符串.这将是每个字符串.
  • 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.

PS:艾哈迈德(Ahmad)有一点要说,如果您的字符串也可能包含字母以外的其他内容,并且您想确保其中的每个 letter 都是小写,而不是要求字符串仅由字母组成,那么您就必须反转字符类,例如:

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]*$") { ... }

在字符类开始的^反转该类,匹配其中包括的每个字符 not .因此,仅当字符串在某处包含大写字母时,此正则表达式才会失败.仍然需要-cmatch.

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.

这篇关于在PowerShell中检查所有小写字母的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆