How can I check a word is already all uppercase?

后端 未结 4 2168
滥情空心
滥情空心 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 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) # => #
    
    b = "GO234"
    b.match(utf_pattern) # => nil
    
    b = "ÜÖ234"
    b.match(utf_pattern) # => nil
    
    b = "Über234"
    b.match(utf_pattern) # => #
    

    Have fun!

提交回复
热议问题