3

I am having some issues in understanding how to use lookbehind in regex. I need to match all between the first preceding occurrence of myMethod and somethingelse

Example https://regex101.com/r/lF8yT0/4

public myMethod
do something

private myMethod
do somethingelse


(?s)(?<=(myMethod){1})(.*)somethingelse

Selects all from the top, while I only expect

private myMethod
do somethingelse

1 Answers1

0

You may use a tempered greedy token:

[^\r\n]*myMethod((?:(?!myMethod).)*?)somethingelse
                 ^^^^^^^^^^^^^^^^^^^  

See the regex demo

The first [^\r\n]* matches 0+ chars other than CR/LF (since you expect the start of the line in your match result) and (?:(?!myMethod).)*? matches any 0 chars (as few as possible) that do not start a myMethod substring.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397