简体   繁体   English

如何使用Ruby的规则验证JavaScript中的正则表达式?

[英]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: 我的数据库中有一些正则表达式,然后在Ruby中将其实例化为:

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. 我想从使用JavaScript将正则表达式提交到我的Rails服务器的表单中验证正则表达式,以显示红色边框,以便以后提交和使用时,它不会在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? 有没有一种简单的方法可以将Ruby的正则表达式引擎的定义赋予JavaScript脚本,从而确定正则表达式在Ruby中是否有效?

The differences between Ruby's regex syntax and JavaScript's can be found here: Differences between Ruby 1.9 and Javascript regexp 可以在这里找到Ruby的regex语法和JavaScript的区别Ruby 1.9和Java regexp的区别

I suggest taking the input string, removing all Ruby features (eg (?#comments...) ) and testing whether it's a valid regex in JavaScript: 我建议使用输入字符串,删除所有Ruby功能(例如(?#comments...) ),并测试它在JavaScript中是否为有效的正则表达式:

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

Removing all Ruby features from the input string will be the tricky bit. 从输入字符串中删除所有Ruby功能将很棘手。

I can't think of an easier way without have some super-long ruby-regex-validating-regexp to hand. 如果没有一些超长的ruby-regex-validating-regexp,我想不出一种更简单的方法。

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 . 这里也提出了类似的问题: 与有效的正则表达式 匹配的正则表达式 ,答案来自RegexBuddy的作者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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