【问题标题】:Regex match everything except words between quotes正则表达式匹配除引号之间的单词以外的所有内容
【发布时间】:2017-08-22 07:45:38
【问题描述】:

我想编写一个正则表达式,它匹配除引号之间的单词之外的所有内容。例如:

 Lorem ipsum "dolor" sit amet, consectetur "adipiscing" elit.
 Nunc ultrices varius odio, "ut accumsan nisi" aliquet vitae.
 "Ut faucibus augue tortor, at aliquam purus dignissim eget."

所以我想要一个匹配以下字符串的正则表达式:

  • Lo​​rem ipsum
  • 坐在一起,consectetur
  • 精英。 Nunc ultrices varius odio,
  • 简历。

我只有以下表达式匹配引号内的子字符串:

([\"'])(?:\\\1|.)*?\1

【问题讨论】:

  • 你目前有什么正则表达式?
  • 我有这个 ([\"'])(?:\\\1|.)*?\1 ,但我想要相反的。与此不匹配的所有内容。
  • 你在使用 PHP/PCRE 吗?试试regex101.com/r/D1WE0g/1
  • 如果您不希望使用转义引号或单引号,也可以试试\G(?:"[^"]*"\K)?[^"]+
  • 我们的建议有效吗?

标签: regex regex-negation


【解决方案1】:

这个正则表达式有效:

([^"]+?)(".*?"|$)

https://regex101.com/r/um9TEx/3

1st Capturing Group ([^"]+?)
Match a single character not present in the list below [^"]+?
+? Quantifier — Matches between one and unlimited times, as few times as possible, expanding as needed (lazy)
" matches the character " literally (case sensitive)
" matches the character " literally (case sensitive)
.*? matches any character (except for line terminators)
*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
" matches the character " literally (case sensitive)

【讨论】:

  • 但它不匹配没有 qoutes 的字符串。
  • 什么意思?
【解决方案2】:

如果你使用 PCRE,你可以使用

([\"'])(?:\\.|(?!\1)[^\\])*?\1(*SKIP)(*F)|(?:[^\\"']|\\.)+

its demo

详情

  • ([\"'])(?:\\.|(?!\1)[^\\])*?\1 - 带有转义引号支持的 "..."'...' 子字符串:
    • ([\"']) - 第 1 组(用 \1 表示):"'
    • (?:\\.|(?!\1)[^\\])*? - 0+ 次出现(由于 *? 很懒,尽可能少):
      • \\. - 转义序列
      • | - 或
      • (?!\1)[^\\] - 除 \ 和第 1 组中的引号字符以外的任何字符
    • \1 - 与第 1 组中的值相同("'
  • (*SKIP)(*F) - PCRE 动词省略当前匹配,使引擎从当前匹配结束位置继续下一个匹配
  • | - 或
  • (?:[^\\"']|\\.)+ - 1 次或多次出现:
    • [^\\"'] - \'" 以外的字符
    • \\. - 转义序列。

【讨论】:

  • 所以任何人都不会花很长时间来弄清楚这部分在 | 之前的所有内容。只是丢弃引号内的所有内容。我什至不知道您可以使用正则表达式丢弃匹配项。
猜你喜欢
  • 2019-11-12
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
相关资源
最近更新 更多