0

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?

2
  • Well I want to check in my code if a submitted regular expression(by the user) is correct. Commented Apr 10, 2014 at 15:10
  • To which field in your db that submitted regular expression save? Commented Apr 10, 2014 at 15:18

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.