Evo_x
Evo_x

Reputation: 3017

Validate correctness of a regular expression - Ruby/Ruby on Rails

Let's say I got a regular expression like this:

/\b[A-Z0-9._%a-zöäüÖÄÜ\-]+@(?:[A-Z0-9a-zöüäÖÜÄ\-]+\.)+[A-Za-z]{2,4}\z/

How can I check via Ruby/RoR if this string is a valid regular expression?

Upvotes: 0

Views: 285

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

If it doesn't raise errors, it's a valid regex. :)

def valid_regex?(str)
  Regexp.new(str)
  true
rescue
  false
end

valid_regex?('[a-b]') # => true
valid_regex?('[[a-b]') # => false

Upvotes: 3

Related Questions