Is this possible with a single regex?

I have a line like

{! texthere }

      

I want to capture either everything after {! until you finish or get to the first}. So what if I had

{! text here} {! text here again} {! more text here. Oh boy!

I would like ["{! Text here}", "{! Text here again}", "{! More text here. Oh boy!" ]

I thought it would work

{!. *} ??

but the above line will output the text ["{! text here} {! text here}} {! more text here. Oh boy!" ]

I'm still very inexperienced with regular expressions, so I don't understand why this doesn't work. I would have thought it would match '{!' followed by any number of characters, as long as you don't end up in a parenthesis (not greedy), which may not be.

+3


source to share


4 answers


You can do it like this:

({![^}]+}?)

      

Regular expression image

Change live in Debuggex



Then restore the capture group $1

that matches the first set of brackets.

Using this way you need to use the "match all" function because the regex itself is made to match one group function

This method does not use any gaze. Also, the use ^}

should limit the number of regex loops, since it looks for the next one }

as a breaker instead of doing the whole expression and then back.

+2


source


Using positive lookbehind (?<={!)[^}]+

:

In [8]: import re

In [9]: str="{!text here} {!text here again} {!more text here. Oh boy!"

In [10]: re.findall('(?<={!)[^}]+',str)
Out[10]: ['text here', 'text here again', 'more text here. Oh boy!']

      



This is a positive lookbehind where any character is }

matched if followed {!

.

+5


source


I believe you want to use the reluctant quantifier:

{!.*?}?

      

This will cause it to .

stop matching as soon as the first is found, the next }

, not the last.

I got a question about greedy and reluctant quantifiers that have a good answer here .

Another option is to specify characters that can appear between two curly braces:

{![^}]*}?

      

Indicates that there cannot be a closing curly brace in your template.

+2


source


if your tool / language supports perl regex try this:

(?<={!)[^}]*

      

+1


source







All Articles