3

I'm looking to see if there is a way to get a match group for each of a comma separated list after a positive lookbehind.

For example

#summertime swimming, running, tanning

Regex (so far)

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

Returns

["swimming, running, tanning"]

Desired Results

["swimming", "running", "tanning"]
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
alairock
  • 1,826
  • 1
  • 21
  • 28

2 Answers2

2

In php you could do this through PCRE verbs (*SKIP)(*F),

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

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • The problem with this that it will even match `swimming, running, tanning` whether there is `#summertime` or not... – HamZa Aug 28 '14 at 09:45
1

The classical way to solve this in PCRE/perl is to use \K escape sequence and the \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

Some notes on the regex:

  • I used the x modifier for white spacing mode.
  • You might need to use the g modifier to match all depending on the language. In php you will need to use preg_match_all().
  • I escaped the hashtag in #summertime because the hashtag is meant for comments in white spacing mode.
  • \G(?<!^) is a classical way of matching from the last point and not from the beginning of string/line. You might also see it in this form \G(?!^) or (?!^)\G. Remember, it's all zero-width.
  • \K is awesome.
  • I used [^\s,]+ but you might as well use \w+ or what ever suits your needs.
  • A bit late but you might as well use your own solution and then split by \s*,\s*

Online demo

Community
  • 1
  • 1
HamZa
  • 14,671
  • 11
  • 54
  • 75