How can I check a word is already all uppercase?

后端 未结 4 2143
滥情空心
滥情空心 2020-12-06 09:16

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


        
相关标签:
4条回答
  • 2020-12-06 09:58
    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.

    0 讨论(0)
  • 2020-12-06 10:05

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

    'go234' == 'go234'.upcase  #=> false
    'GO234' == 'GO234'.upcase  #=> true
    
    0 讨论(0)
  • 2020-12-06 10:11

    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!

    0 讨论(0)
  • 2020-12-06 10:12

    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

    0 讨论(0)
提交回复
热议问题