简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM