如何将ruby regex翻译为javascript? - (?i-mx:..)和Rails 3.0.3 [英] How to translate ruby regex to javascript? - (?i-mx:..) and Rails 3.0.3

查看:75
本文介绍了如何将ruby regex翻译为javascript? - (?i-mx:..)和Rails 3.0.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用validates_format_of方法检查电子邮件格式:

Im using validates_format_of method to check email format:

validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

我也使用livevalidation插件验证表格,所以在我的代码中我得到:

also Im using livevalidation plugin to validate forms, so in my code Im getting:

(?i-mx:^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$)

Javascript无法读取此正则表达式。如何或在哪里我可以将此正则表达式更改为原始:

Javascript cant read this regex. How or where I can change this regex to be as original:

/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

推荐答案

Ruby和JavaScript正则表达式由具有不同功能的不同引擎解析和执行。因此,Ruby和JavaScript正则表达式之间存在细微的差异,这些差异略微不相容。如果您注意不直接翻译,您仍然可以用JavaScript表示简单的Ruby正则表达式。

Ruby and JavaScript regular expressions are parsed and executed by different engines with different capabilities. Because of this, Ruby and JavaScript regular expressions have small, subtle differences which are slightly incompatible. If you are mindful that they don't directly translate, you can still represent simple Ruby regular expressions in JavaScript.

这是客户端验证的作用

class Regexp
  def to_javascript
    Regexp.new(inspect.sub('\\A','^').sub('\\Z','$').sub('\\z','$').sub(/^\//,'').sub(/\/[a-z]*$/,'').gsub(/\(\?#.+\)/, '').gsub(/\(\?-\w+:/,'('), self.options).inspect
  end
end

最近< a href =http://www.edgerails.info/2013/1/21/whats-new-55/ =nofollow noreferrer>将路线检查员添加到铁路需要类似的方法,可能更好,因为它避免了猴子修补:

The recent addition of the routes inspector to rails takes a similar approach, perhaps even better as it avoids monkey patching:

def json_regexp(regexp)
  str = regexp.inspect.
        sub('\\A' , '^').
        sub('\\Z' , '$').
        sub('\\z' , '$').
        sub(/^\// , '').
        sub(/\/[a-z]*$/ , '').
        gsub(/\(\?#.+\)/ , '').
        gsub(/\(\?-\w+:/ , '(').
        gsub(/\s/ , '')
  Regexp.new(str).source
end

然后将这些内容插入到您的javascript代码中,请使用以下内容:

Then to insert these into your javascript code, use something like:

var regexp = #{/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.to_javascript};

这篇关于如何将ruby regex翻译为javascript? - (?i-mx:..)和Rails 3.0.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆