【问题标题】:Positive lookbehind followed by comma separated list正向后视后跟逗号分隔列表
【发布时间】:2014-10-21 20:40:48
【问题描述】:

我正在寻找是否有办法在积极的后视之后为每个逗号分隔列表获取匹配组。

例如

#summertime swimming, running, tanning

正则表达式(到目前为止)

(?<=#summertime\s)(.+)

返回

["swimming, running, tanning"]

期望的结果

["swimming", "running", "tanning"]

【问题讨论】:

  • 我认为你最好用, 分割你目前得到的字符串。
  • 你使用什么语言?

标签: regex


【解决方案1】:

在 PCRE/perl 中解决这个问题的经典方法是使用 \K escape sequence\G anchor

(?:                 # non-capturing group
   \#summertime\b   # match #summertime
   |                # or
   \G(?<!^),        # a comma not at the beginning of string and match it only if it's after the last match
)                   # closing the non-capturing group
\s*                 # some optional whitespaces
\K                  # forget what we matched so far
[^\s,]+             # match anything that's not a whitespace nor a comma one or more times

关于正则表达式的一些注意事项:

  • 我将x 修饰符用于空白间距模式。
  • 您可能需要使用g 修饰符来匹配所有内容,具体取决于语言。在 php 中,您需要使用 preg_match_all()
  • 我转义了 #summertime 中的主题标签,因为该主题标签适用于空白间距模式下的 cmets。
  • \G(?&lt;!^) 是从最后一点而不是从字符串/行的开头进行匹配的经典方式。您可能还会以\G(?!^)(?!^)\G 的形式看到它。请记住,这都是零宽度。
  • \Kawesome
  • 我使用了[^\s,]+,但您也可以使用\w+ 或任何适合您需要的方式。
  • 有点晚了,但您不妨使用自己的解决方案,然后按\s*,\s* 拆分

Online demo

【讨论】:

    【解决方案2】:

    在php中你可以通过PCRE动词(*SKIP)(*F)来做到这一点,

    (?:^(?:(?!#summertime).)*$|^.*?#summertime)(*SKIP)(*F)|\w+
    

    DEMO

    【讨论】:

    • 这个问题,不管有没有#summertime,它都会匹配swimming, running, tanning...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    相关资源
    最近更新 更多