【问题标题】:Match everything between optional single or double quotation marks匹配可选单引号或双引号之间的所有内容
【发布时间】:2020-08-05 13:50:50
【问题描述】:

我正在开发一个正则表达式来解析 JSON 响应中的值,但我在处理一个字段时遇到了问题,因为它包含人工编写的文本,因此,由于内容可能会发生变化并破坏正则表达式,我需要一个正则表达式将匹配以下所有潜在值:

, 'resolve_comment': "This value's comment contains an apostrophe / single quotation mark so it will be automatically enclosed in double quotation marks", 
, 'resolve_comment': 'Some comments, like this one, contain a comma. If there is no comment then there will be no quotation marks as you can see below.', 
, 'resolve_comment': None, 

我在网上找到的所有正则表达式都不适用于所有这 3 个场景。

我得到的最接近的是:

  1. 'resolve_comment': (?:(?:"(?P<resolve_comment>[^"]*)")|(?:'(?P<resolve_comment>[^']*)')|(?P<resolve_comment>None)), 但系统不允许重复的捕获组名称。
  2. 'resolve_comment': (?:(?:"([^"]*)")|(?:'([^']*)')|(None)), 但这创建了 3 个捕获组,其中只有一个被填充。
  3. 'resolve_comment': ["|']?(.*)["|']?, 但这会留下一个不理想的尾随引号。

【问题讨论】:

  • 什么是“系统”?
  • 进行解析的系统是 Splunk。
  • 'resolve_comment':\s*(?P<resolve_comment>"[^"]*"|'[^']*'|None), 然后用| eval text = replace(text,"^['\"]|['\"]$", "")(或resolve_comment)替换第一个和最后一个引号呢? Splunk 没有分支重置组,您也不能使用同名组
  • 谢谢,但也许我应该进一步澄清,解析是作为自定义插件的字段提取阶段的一部分完成的,而不是我可以使用函数的搜索。
  • 如果支持条件构造,您可以使用 regex101.com/r/Z3ZKg2/1 将其捕获到第 2 组。

标签: regex splunk


【解决方案1】:

这是我的正则表达式,它匹配你所有的潜在值,试试这个:

(?<=").*(?=")|(?<=').*(?=')|None

所以我匹配“”和“”之间的所有内容以及值“无”。 考虑到这里无效,它不匹配像 '" 这样的字符串。 在这里看到它:https://regex101.com/r/yV9GES/1

告诉我你是否在寻找其他东西?

【讨论】:

  • 第一个例子的撇号破坏了这个正则表达式。不过,谢谢。
  • 我试过了,它似乎在这里工作:regex101.com/r/yV9GES/2
  • 是的,当只有值存在但整个文本存在时它才有效,所以'resolve_comment' 会破坏它。
  • 好的……你也想包含“resolve_comment”……对不起,我看错了。让我试试看。
  • 试试这个:'resolve_comment': (?:["|']?(.*)["|']|(None)) /gm。它应该可以工作。
猜你喜欢
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2018-03-17
相关资源
最近更新 更多