开发者

Continuing at the end of the previous match in RegEx (PCRE)

I'm trying to prevent the \G anchor from matching the beginning of the string. I only want it to match at the end of the last regex match.

Given the following text:

Pig, Cow, Goat
fruit: apple, orange, peach, pear
vegetable: Carrot, Lettuce, Cellery

And this pattern:

(fruit:|\G)([\w]+|[\, ])

I want it to only match words after "fruit:", but I need it to capture each word individua开发者_如何学Pythonlly. If I just put a + at the very end of this pattern, it would match all the words after "fruit:" but it would only capture "pear" as each iteration of + stomps on the last.

Here's the problem. This pattern works, except it also matches "Pig, Cow and Goat" because \G will match the end of the last match OR the beginning of the whole string. How can I prevent it from matching the beginning of the whole string?

I'm using PCRE in PHP and I've been using Rubular.com to help me do quick tests.


To my eye, you're regex was not giving you what you said you wanted. You said you wanted each word following "fruit: ". Given your example, I don't think your first attempt was really giving you that. Try:

(?:fruit:\s*|\G,\s*)(\w+)

If you match all, that should give you the words without the whitespace or punctuation.

Here's a rundown:

  • (?: - start non-capturing group
  • fruit:\s* - the preamble for a good match
  • | - or
  • \G,\s*) - the last match position, a comma and zero or more whitespace
  • (\w+) capture one or more word characters

EDIT:

To prevent the case where you get a match on the first line, if the first line starts with a comma followed by one or more comma-separated words, just add a negative zero-width look-behind on the start anchor just before the \G:

(?:fruit:\s*|(?<!^)\G,\s*)(\w+)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜