【问题标题】:Get all the text between quotes matching one of the word获取与单词之一匹配的引号之间的所有文本
【发布时间】:2020-10-20 09:07:09
【问题描述】:
a:5:{s:12:"SubmissionID";s:0:"";s:13:"NotesClientID";s:4:"1891";s:5:"Field";a:5:
{i:0;s:7:"8/19/19";i:1;s:0:"";i:4;s:0:"";i:5;s:160:"client is dismissed due to no contact with me or with his assigned Recovery
Coach";i:7;s:0:"";}s:10:"SecurityID";s:40:"a31b7ea7f9191465525d0ac9a6358ba7b3d3e0fc";s:13:"action_doSave";s:4:"Save";}

在上面的字符串中,预期的输出是“客户因没有与我或他指定的康复教练联系而被解雇”

这包含 dismissed 字。

同样,正则表达式应该选择字符串中包含被解雇/出院/服从之一的字符串。

我已经在https://rubular.com/r/QMFAHjUgaYdjpM尝试过这个

【问题讨论】:

  • 如果没有必要,请不要链接到屏幕截图。将您要讨论的正则表达式作为文本发布。另外,我从您的问题中不明白,您感兴趣的子字符串的开头是如何定义的,因为您的字符串中有几个带引号的子字符串。
  • @user1934428,据我了解,OP 希望提取一个由双引号括起来的字符串,其中包含三个指定单词中的任何一个且没有双引号。阿卡什,对吗?每当您给出示例时,您都应该显示所需的结果。我建议您进行编辑以澄清。
  • @AkashK :如果有多个字符串与标准匹配,还要澄清效果。你想得到一个包含所有匹配字符串的数组吗?

标签: regex ruby string


【解决方案1】:

您可以使用以下正则表达式匹配所需的文本。

/.*?"(?=(?:[^"]*\bdismissed\b[^"]*"))\K[^"]*(?=")/m

Start your engine!

regex1011 提供了有关正则表达式每个元素的详细信息。

如果变量str 包含问题中作为示例给出的文本,则可以这样写:

str.scan(/.*?"(?=(?:[^"]*\bdismissed\b[^"]*"))\K[^"]*(?=")/m)
  #=> ["client is dismissed due to no contact with me or with his assigned Recovery\nCoach"]

[String#scan] 返回一个包含正则表达式的每个匹配项的数组。这里有一个匹配项。

Ruby 的正则表达式引擎执行以下操作。

/
.*?                : match 0+ characters, lazily
"                  : match a double-quote
(?=                : begin a positive lookahead to assert that
                     'dismissed' appears before the next double-quote
  (?:              : begin a non-capture group
    [^"]*          : match 0+ characters other than double-quotes
    \bdismissed\b  : match 'dismissed'
    [^"]*          : match 0+ characters other than double-quotes
    "              : match a double-quote
  )                : end non-capture group
)                  : end positive lookahead
\K                 : forget all matched so far and reset match
[^"]*              : match 0+ characters other than double-quotes
(?=")              : assert the next character is a double-quote
/m                 : multiline mode to match line terminators

附录:我错过了问题中提到的目标词可能是“dismissed”、“discharged”或“amenable”中的任何一个。与其修改我的答案,不如说在哪里

\bdismissed\b

出现在应该替换为的正则表达式中

\b(?:dismissed|discharged|amenable)\b

1.移动光标查看详细说明。

【讨论】:

  • 我认为您需要添加可能的其他 dismissed/discharged/amenable 关键字。我在想这样的事情:rubular.com/r/B4xaGhdbrR3k8p
  • @MDR,感谢您的提醒。我快速浏览了您提供的链接,您在其中使用了捕获组。这似乎工作得很好,虽然我有一个不合理的偏好,只在可能的情况下进行匹配。一个小细节:你不需要转义双(或单)引号。
猜你喜欢
  • 1970-01-01
  • 2019-03-11
  • 2021-07-10
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
相关资源
最近更新 更多