Search code examples
regexregex-lookarounds

Regex: negative lookbehind


using regex: (?<!map)\s+.collect\(Collectors.toL

To match:

  1. all 2 line strings where the first line does not have "map"
  2. And the second line has collect(Collectors.toL

Use a negative lookbehind, but as you can see in the link below, the second test is also being matched.

How do we update so as to match as specified above?

https://regex101.com/r/SBJahj/2


Solution

  • You negative lookbehind condition isn't correct because .map can have many characters before matching .collect. Besides a negative lookbehind with dynamic length isn't supported in most of regex flavors.

    You may use this regex with a negative lookahead:

    ^(?!\s*\.map).+\n\s*\.collect\(Collectors\.toL
    

    RegEx Demo

    Here:

    • ^: Start
    • (?!\s*\.map): Fail the match if we have .map after 0 or more whitespaces
    • .+\n: Match 1+ chars followed by a line break
    • \s*\.collect\(Collectors\.toL: Match your desired text in a new line