Regex to capture an optional group in the middle of a block of input

后端 未结 3 2035
梦如初夏
梦如初夏 2021-01-16 08:03

I\'m stuck on a RegEx problem that\'s seemingly very simple and yet I can\'t get it working.

Suppose I have input like this:

Some text %interestingbi         


        
3条回答
  •  独厮守ぢ
    2021-01-16 08:33

    Try this:

    %interestingbit%(?:(.+)(?OPTIONAL_THING))?(.+?)%anotherinterestingbit%
    

    First there's a non-capturing group which matches .+OPTIONAL_THING or nothing. If a match is found, there's the named group inside, which captures OPTIONAL_THING for you. The rest is captured with .+?%anotherinterestingbit%.

    [edit]: I added a couple of parentheses for additional capture groups, so now the captured groups match the following:

    • $1 : text before OPTIONAL_THING or nothing
    • $2 or $optionalCapture : OPTIONAL_THING or nothing
    • $3 : text after OPTIONAL_THING, or if OPTIONAL_THING is not found, the full text between %interestingbit% and %anotherinterestingbit%

    Are these the three matches you're looking for?

提交回复
热议问题