2

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The differences between the 2 engines seem small enough that I think I will just try to parse it in JavaScript.
1

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.

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.