开发者

Checking whether two or more consecutive letters are uppercase

开发者 https://www.devze.com 2023-03-02 05:14 出处:网络
I\'m trying to create a function in Ruby that checks whether a strin开发者_Go百科g has two or more consecutive uppercase letters, example:

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,}/
0

精彩评论

暂无评论...
验证码 换一张
取 消