Home > Enterprise >  Regex how to select first instance of pattern in repeating pattern
Regex how to select first instance of pattern in repeating pattern

Time:05-09

I have a string in which I need to find all instances of the following pattern:

{{.*Sm_.*}}

The problem I am having is this pattern repeats throughout the string, so when I try and do a non greedy match by doing:

{{.*Sm_.*?}}

It matches everything from the first to the last instance of this pattern, including a bunch of stuff that I don't want it to match. Essentially the string looks something like this:

{{.*Sm_.*}} Bunch of content {{.*Sm_.*}} More content {{.*Sm_.*}}

And that's repeating. I only want to capture the sections that match the pattern without capturing anything else. How can I do that?

CodePudding user response:

The following non greedy pattern will only target the {{...}} terms themselves, will spilling over across any content.

\{\{[^}]*Sm_.*?\}\}

Demo

CodePudding user response:

. and * are actual regex characters, so you'll need to escape them if you want the pattern to match. The pattern you want is this: {{\.\*Sm_\.\*}}

Edit: I misunderstood the question. Tim Biegeleisen has the right answer for your question.

  • Related