Home > Net >  C# Regex, Check previous line for subpattern THEN continue matching only if subpattern matches on th
C# Regex, Check previous line for subpattern THEN continue matching only if subpattern matches on th

Time:12-22

I want to exclude lines that have a "#-hide-" comment on the previous line which i can do with a modification of this script:

(?m)^(?<!^#-hide-\r?\n). 

And I also want to match the text between "func\s " and "s*\(" (i.e. matching only "function_name" out of "func function_name():")

This works with:

(?<=func\s ). (?=\s*\()

But trying to combine the two by doing (?m)^(?<!^#-hide-\r?\n)(?<=func\s ). (?=\s*\() doesn't work.


overall:

func include_me():

#-hide-
func exclude_me():

func include_me2():

Should match "include_me" and "include_me2"

CodePudding user response:

You can use

(?m)(?<=(?<!^#-hide-[\r\n] )func\s ). ?(?=\s*\()

See the regex demo. Details:

  • (?m) - an inline RegexOptions.Multiline regex option
  • (?<=(?<!^#-hide-[\r\n] )func\s ) - a positive lookbehind that requires the following pattern to match immediately to the left of the current location:
    • (?<!^#-hide-[\r\n] ) - a negative lookbehind that fails the match if there is start of a line (^), #-hide- text and then one or more CR or LF chars ([\r\n] )
    • func\s - func and one or more whitespaces
  • . ? - one or more chars other than LF chars, as few as possible
  • (?=\s*\() - a positive lookahead that requires zero or more whitespace chars and then a ( char immediately to the right of the current location.
  • Related