Skip to content
Advertisement

Regex lookaround start of line

I have this regex https://regex101.com/r/wRBBAz/1

(?<=s|^|.)[^ .]+(?=s*(())

Testing with input

test1 {...}
test2();

I specified start of line (^) in lookaround so I don’t understand why it selects

}
test2

instead of only

test2

Advertisement

Answer

The problem is that [^ .] matches any char but a space and a dot, that is, it matches line break chars.

You can use

(?<![^.s])[^s.]+(?=s*(())

See the regex demo

Details

  • (?<![^.s]) – a negative lookbehind that matches a location that is either at the start of string or immediately preceded with a dot or whitespace
  • [^s.]+any one or more chars other than whitespace and .
  • (?=s*(()) – a positive lookahead making sure there is zero or more whitespces and then a ( (captured into Group 1) immediately to the right of the current location.
Advertisement