davidraedev
davidraedev

Reputation: 119

Regex with negative lookahead still matching

I'm trying to test for a shebang "#!" to see if it doesn't have a forward slash on either side with this regex (?!\/)#\!(?!\/)

It should match: #!, z#!, #!z, z#!z

It should not match: /#!, #!/, /#!/

I put negative lookaheads around the shebang so it won't match any slashes, and indeed it doesn't match trailing slashes, but for some reason it is still matching leading slashes /#!.

example on regexr

Any ideas on why this is happening / how to fix it?

Upvotes: 2

Views: 665

Answers (1)

hwnd
hwnd

Reputation: 70722

You want to use a combination of Negative Lookbehind and Negative Lookahead.

(?<!/)#!(?!/)

Explanation:

(?<!     # look behind to see if there is not:
  /      #   '/'
)        # end of look-behind
#!       # '#!'
(?!      # look ahead to see if there is not:
  /      #   '/'
)        # end of look-ahead

Upvotes: 4

Related Questions