Checking whether two or more consecutive letters are uppercase
I'm trying to create a function in Ruby that checks whether a strin开发者_Go百科g has two or more consecutive uppercase letters, example:
"Hello There" # => returns false
"Hello ThERe" # => returns true
"Hello There" =~ /[A-Z]{2}/
# => nil
"Hello ThERe" =~ /[A-Z]{2}/
# => 8
This will return nil if it doesn't have the letters, or an index of the first occurence otherwise (you can treat these as true/false)
def has_two_uppercase_letters
str =~ /[A-Z]{2}/
end
Or if you want to return an explicit true/false:
def has_two_uppercase_letters
(str =~ /[A-Z]{2}/) != nil
end
string =~ /[A-Z]{2,}/
Match in the set "A" to "Z" 2 or more times.
You can test this on http://rubular.com/
Because Ruby doesn’t support \p{upper}
, you have to use
/\p{Lu}{2,}/
精彩评论