简体   繁体   中英

How do I validate a regular expression in JavaScript using Ruby's rules?

I have some regular expressions in my database which are then instantiated in Ruby with something like:

rx = Regexp.new(rx_string)

I want to validate the regular expression from right within the form that submits it to my Rails server using JavaScript, to display a red border, so that when submitted and used later on, it will not raise an exception in Ruby.

Is there an easy way of giving Ruby's regular expression engine's definition to a JavaScript script that will come up with a true or false on whether the regex is valid in Ruby?

The differences between Ruby's regex syntax and JavaScript's can be found here: Differences between Ruby 1.9 and Javascript regexp

I suggest taking the input string, removing all Ruby features (eg (?#comments...) ) and testing whether it's a valid regex in JavaScript:

try {
  RegExp(input); valid = true;
} catch(e) {
  valid = false;
}

Removing all Ruby features from the input string will be the tricky bit.

I can't think of an easier way without have some super-long ruby-regex-validating-regexp to hand.

No this is not possible (within a single regex), since you can write within your pattern nearly everything and its valid and you can nest your expressions as you like it.

Of course it would be possible to write a parser that parses the regex, but I am quite sure you don't want to do that.

A similar question has been asked here: Regexp that matches valid regexps , where the answer came from the author of RegexBuddy .

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