How can I check a word is already all uppercase in

2019-01-18 18:06发布

问题:

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

回答1:

You can compare the string with the same string but in uppercase:

'go234' == 'go234'.upcase  #=> false
'GO234' == 'GO234'.upcase  #=> true

Hope this helps



回答2:

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.

Thank you @mu is too short mentioned that we should use /\p{Lower}/ instead to match non-English lower case letters.



回答3:

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).

However if you want to use it for strings like "Überall", just add this slight modification:

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!



回答4:

You could either compare the string and string.upcase for equality (as shown by 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)

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