【问题标题】:Regular expression in form of string not working in Ruby字符串形式的正则表达式在 Ruby 中不起作用
【发布时间】:2022-01-09 23:16:09
【问题描述】:

我将正则表达式存储在一个变量中 - 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

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

【问题讨论】:

  • 将正则表达式模式传递给数据库时,将其保存为纯字符串。然后,从 DB 中获取它时,使用 Regexp 构造函数。
  • @WiktorStribiżew 你能帮我把这个/\A([^@\s]+)@((?:a-b+\.)+(in|com))\z/ 正则表达式转换成纯字符串吗?
  • 我用例子添加了一个完整的答案。

标签: regex ruby string


【解决方案1】:

使用单引号而不是双引号 (cf 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

【讨论】:

  • ...或Regexp.new("\\A([^@\\s]+)@((?:a-b+\\.)+(in|com))\\z") #=> /\A([^@\s]+)@((?:a-b+\.)+(in|com))\z/
【解决方案2】:

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

因此,如果您打算使用单个列来存储正则表达式数据,您可以使用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 取回正则表达式对象:

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

请参阅 Regexp Ruby 文档。

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 2012-10-02
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2014-02-12
    相关资源
    最近更新 更多