ruby 如何检查一个单词是否已经全部大写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8529595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check a word is already all uppercase?
提问by Jacob
I want to be able to check if a word is already all uppercase. And it might also include numbers.
我希望能够检查一个单词是否已经全部大写。它也可能包括数字。
Example:
例子:
GO234 => yes
Go234 => no
回答by JCorcuera
You can compare the string with the same string but in uppercase:
您可以将字符串与相同的字符串进行比较,但要大写:
'go234' == 'go234'.upcase #=> false
'GO234' == 'GO234'.upcase #=> true
回答by PeterWong
a = "Go234"
a.match(/\p{Lower}/) # => #<MatchData "o">
b = "GO234"
b.match(/\p{Lower}/) # => nil
c = "123"
c.match(/\p{Lower}/) # => nil
d = "μ"
d.match(/\p{Lower}/) # => #<MatchData "μ">
So when the match result is nil, it is in uppercase already, else something is in lowercase.
所以当匹配结果为 nil 时,它已经是大写的,否则有些东西是小写的。
Thank you @mu is too short mentioned that we should use /\p{Lower}/ instead to match non-English lower case letters.
谢谢@mu 提到我们应该使用 /\p{Lower}/ 来匹配非英文小写字母太短了。
回答by Ole Spaarmann
I am using the solution by @PeterWong and it works great as long as the string you're checking against doesn't contain any special characters (as pointed out in the comments).
我正在使用@PeterWong 的解决方案,只要您检查的字符串不包含任何特殊字符(如评论中指出的那样),它就可以很好地工作。
However if you want to use it for strings like "überall", just add this slight modification:
但是,如果您想将它用于像“überall”这样的字符串,只需添加以下细微修改:
utf_pattern = Regexp.new("\p{Lower}".force_encoding("UTF-8"))
a = "Go234"
a.match(utf_pattern) # => #<MatchData "o">
b = "GO234"
b.match(utf_pattern) # => nil
b = "ü?234"
b.match(utf_pattern) # => nil
b = "über234"
b.match(utf_pattern) # => #<MatchData "b">
Have fun!
玩得开心!
回答by Gishu
You could either compare the string and string.upcase for equality (as shown by JCorc..)
您可以比较字符串和 string.upcase 是否相等(如 JCorc 所示..)
irb(main):007:0> str = "Go234"
=> "Go234"
irb(main):008:0> str == str.upcase
=> false
OR
或者
you could call arg.upcase! and check for nil. (But this will modify the original argument, so you may have to create a copy)
你可以打电话给 arg.upcase!并检查是否为零。(但这会修改原始参数,因此您可能需要创建一个副本)
irb(main):001:0> "GO234".upcase!
=> nil
irb(main):002:0> "Go234".upcase!
=> "GO234"
Update: If you want this to work for unicode.. (multi-byte), then string#upcase won't work, you'd need the unicode-util gem mentioned in this SO question
更新:如果你希望它适用于 unicode ..(多字节),那么 string#upcase 将不起作用,你需要这个 SO question 中提到的 unicode-util gem

