代码之家  ›  专栏  ›  技术社区  ›  Sourabh Banka

字符串形式的正则表达式在Ruby中不起作用

  •  0
  • Sourabh Banka  · 技术社区  · 3 年前

    我把正则表达式存储在变量中- s="/\A([^@\s]+)@((?:a-b+\.)+(in|com))\z/" .

    "sourabh@a-b.in".match?(/\A([^@\s]+)@((?:a-b+\.)+(in|com))\z/) => returns true
    Regexp.new(s) => returns /\/A([^@ ]+)@((?:a-b+.)+(in|com))z\//
    "sourabh@a-b.in".match?(Regexp.new(s)) => returns false
    

    将正则表达式存储在数据库中时 \ 自动删除。 我将以字符串的形式获取正则表达式验证器。不知道为什么它不起作用?

    0 回复  |  直到 3 年前
        1
  •  0
  •   joel1di1    3 年前

    使用单引号而不是双引号(参见 this page )

    > puts "/\A([^@\s]+)@((?:a-b+\.)+(in|com))\z/"
    /A([^@ ]+)@((?:a-b+.)+(in|com))z/
    
    > puts '/\A([^@\s]+)@((?:a-b+\.)+(in|com))\z/'
    /\A([^@\s]+)@((?:a-b+\.)+(in|com))\z/
    

    然后删除开头和结尾“/”:

    > s = '\A([^@\s]+)@((?:a-b+\.)+(in|com))\z'
    => "\\A([^@\\s]+)@((?:a-b+\\.)+(in|com))\\z"
    
    > reg = Regexp.new s
    => /\A([^@\s]+)@((?:a-b+\.)+(in|com))\z/
    
    > "sourabh@a-b.in".match?(Regexp.new(reg))
    => true
    
    
        2
  •  0
  •   Wiktor Stribiżew    3 年前

    当需要在数据库中存储正则表达式模式时,一种常见的方法是将模式/标志存储为 一串 .

    因此,如果要使用单个列存储正则表达式数据,可以使用 Regexp#to_s :

    regex_string = /.../.to_s
    

    如果你想储存图案( source )还有旗帜( options )作为单独的字符串:

    regex_pattern = /\A([^@\s]+)@((?:a-b+\.)+(in|com))\z/.source
    regex_flags = /\A([^@\s]+)@((?:a-b+\.)+(in|com))\z/.options
    

    从数据库中读取值后,可以使用 Regexp.new constructor 要取回regex对象,请执行以下操作:

    rx = Regexp.new(regex_string)
    # or
    rx = Regexp.new(regex_pattern, regex_flags)
    

    看见 Regexp Ruby文档。

    推荐文章