openlang

从已保存的字符串构造时 Ruby 正则表达式无法工作

我把一个正则表达式保存在下面的变量里。 pattern_text = "/\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/"。

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

把这个正则表达式保存到数据库时,\ 会自动消失。 我收到的正则验证器是字符串形式。为什么这个版本无法工作?

从英语翻译查看原文

后续讨论 2

顺着彼此的依据读下去
  1. 固定链接

    请选择单引号字符串,而不是双引号字符串(参见这个说明 (https://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes))。

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

    接着,去掉两端的 '/'。

    > pattern_text = '\A([^@\s]+)@((?:c-d+\.)+(in|com))\z'
    => "\\A([^@\\s]+)@((?:c-d+\\.)+(in|com))\\z"
    
    > compiled = Regexp.new(pattern_text)
    => /\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/
    
    > "mailbox@c-d.in".match?(Regexp.new(compiled))
    => true
    从英语翻译查看原文
  2. 固定链接

    要把正则表达式模式放进数据库留待以后使用,通常会保存模式 / 标志的字符串表示。

    所以,如果所有正则信息都放在同一列,可以使用 Regexp#to_s (https://ruby-doc.org/core-2.5.1/Regexp.html#method-i-to_s)。

    stored_expression = /.../.to_s

    如果想把模式 (source (https://ruby-doc.org/core-2.5.1/Regexp.html#method-i-source)) 和标志 (options (https://ruby-doc.org/core-2.5.1/Regexp.html#method-i-options)) 分别保存成字符串。

    stored_pattern = /\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/.source
    stored_flags   = /\A([^@\s]+)@((?:c-d+\.)+(in|com))\z/.options

    从数据库取回这些值后,用 Regexp.new 构造函数 (https://ruby-doc.org/core-2.5.1/Regexp.html#method-c-new) 重新创建正则对象。

    expression = Regexp.new(stored_expression)
    # alternatively
    expression = Regexp.new(stored_pattern, stored_flags)

    请查阅 Ruby 的 Regexp 文档 (https://ruby-doc.org/core-2.5.1/Regexp.html)。

    从英语翻译查看原文

同一个问题的其他角度

  1. 调用 String.Format 时怎样转义百分号?

    我的 strings.xml 文件保存了一个 SQL 查询,我想在代码中用 String.Format 构造最终字符串。SELECT 查询中有一个类似下面这样的 like 子句。 为了格式化,我用 %1$s 替换 'pattern',得到下面这样。…

    回复 3最近活动 java
  2. 在 F# 中格式化字符串

    我正在第一次编写 F# 库 使用 string.Format 时,提示说这个函数不存在。 是我哪里弄错了,还是本来就不能用?

    回复 2最近活动 fsharp
  3. 提取 tcl 字符串中的一部分

    我想用 tcl 拆开 Reports/Report#2.rpt,只留下 Report#2.rpt。我试了下面的办法,但运行时没有得到任何输出。

    回复 2最近活动 tcl