1

I need a regex expression that finds a match when the sentence "SENTENCE TO MATCH" is found between "START1" and the first "end". the problem I have got is that the search should stop at the first "end" (that is related to START1). The expression that I worked out so far:

START1[\s\S]asterix?SENTENCE TO MATCH[\s\S]*?end

works in this case:

START1

text

SENTENCE TO MATCH

text

end

START2

text

end

but it gives me a false positive in this case where I want a no match

START1

text

end

START2

text

SENTENCE TO MATCH

text

end

any help is much appreciated. thanks

gmuretto
  • 11
  • 2
  • Use `START1(?:(?!START1).)*?SENTENCE TO MATCH.*end` - see https://regex101.com/r/HLMTRJ/1. Note that `[\s\S]` matches any char, and you want the match to occur on a single line only, so use `.`. – Wiktor Stribiżew Dec 23 '20 at 12:37
  • thanks Wiktor, sorry this is my first post. I edited it to make it in different lines – gmuretto Dec 23 '20 at 12:46
  • It is the same, only with all quantifiers set to lazy, use `START1(?:(?!START1).)*?SENTENCE TO MATCH.*?end` with the `s` flag, see https://regex101.com/r/HLMTRJ/2 – Wiktor Stribiżew Dec 23 '20 at 13:26
  • Thanks Wiktor but I still get the false positive in the second example. (In the link that you created there are two matches, I would need only one). Is there a way to terminate the search after the first "end"? that's basically what I need – gmuretto Dec 23 '20 at 14:08
  • Remove `g` flag, see https://regex101.com/r/HLMTRJ/3. Extract/replace the first match only, use the corresponding method – Wiktor Stribiżew Dec 23 '20 at 14:09
  • Cheers Wictor that's a progress. but if i put only the second example (below) in the test I still get a match. Can we put a stop after the first "end" following START1? START1 text end START2 text SENTENCE TO MATCH text end – gmuretto Dec 23 '20 at 15:39
  • https://regex101.com/r/HLMTRJ/4 - I think you would understand it if you read the linked answer. – Wiktor Stribiżew Dec 23 '20 at 17:09
  • 1
    That works beautifully, thank you very much Wictor you are a star!!! – gmuretto Dec 23 '20 at 17:25

0 Answers0