Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether two or more consecutive letters are uppercase

Tags:

regex

ruby

I'm trying to create a function in Ruby that checks whether a string has two or more consecutive uppercase letters, example:

"Hello There"  # => returns false
"Hello ThERe"  # => returns true
like image 463
wsb3383 Avatar asked Dec 13 '22 13:12

wsb3383


2 Answers

"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
like image 69
Dylan Markow Avatar answered Dec 15 '22 05:12

Dylan Markow


string =~ /[A-Z]{2,}/

Match in the set "A" to "Z" 2 or more times.

You can test this on http://rubular.com/

like image 42
bheeshmar Avatar answered Dec 15 '22 04:12

bheeshmar