我希望能够检查一个单词是否已经全部大写。它还可能包含数字。
示例:
GO234 => yes
Go234 => no
发布于 2011-12-16 12:00:13
您可以将字符串与相同的字符串进行比较,但以大写字母表示:
'go234' == 'go234'.upcase #=> false
'GO234' == 'GO234'.upcase #=> true
发布于 2011-12-16 12:01:33
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 "µ">
因此,当匹配结果为nil时,它已经是大写的,否则就是小写的。
谢谢@mu太短了,我们应该使用/\p{ lower }/来匹配非英文小写字母。
发布于 2012-07-10 22:47:57
我正在使用@PeterWong的解决方案,只要您检查的字符串不包含任何特殊字符(如注释中所指出的),它就很有效。
但是,如果你想把它用于像“use”这样的字符串,只需稍微修改一下就行了:
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">
玩得开心!
https://stackoverflow.com/questions/8529595
复制相似问题