积极lookbehind其次逗号分隔列表
问题描述:
我期待看看是否有一种方法来获得一个匹配组的每个逗号分隔列表后积极lookbehind。积极lookbehind其次逗号分隔列表
例如
#summertime swimming, running, tanning
正则表达式(到目前为止)
(?<=#summertime\s)(.+)
返回
["swimming, running, tanning"]
期望的结果
["swimming", "running", "tanning"]
答
的传统方式在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()
。 - 我逃过的标签,因为hashtag是用于白色间隔模式下的评论。
-
\G(?<!^)
是从最后一点开始匹配的经典方法,而不是从字符串/行的开头进行匹配。你也可以用这种形式看到它\G(?!^)
或(?!^)\G
。请记住,这全是零宽度。 -
\K
是awesome。 - 我用
[^\s,]+
,但你也可以使用\w+
或什么都适合你的需要。 - 有点晚了,但你还不如用自己的解决方案,然后通过
\s*,\s*
我想你最好还是分割字符串你目前与'得到的,'分裂。 – NigoroJr 2014-08-28 05:42:31
你在用什么语言? – Toto 2014-08-28 07:19:11