Reputation: 8595
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?
Upvotes: 2
Views: 435
Reputation: 92976
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.
Upvotes: 1
Reputation: 111900
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 (e.g. (?#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.
Upvotes: 3