Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this regular expression mean: (?![#$])

Can someone give me an example/explanation what this regular expression does:

(?![#$])

This is part of <%(?![#$])(([^%]*)%)*?> which is what ASP.NET uses to parse server-side code blocks. I understand the second part of the expression but not the first.

I checked the documentation and found (?! ...) means a zero-width negative lookahead but I'm not entirely sure I understand what that means. Any input I tried so far that looks like <% ... %> seems to work - I wonder why this first sub-expression is even there.

Edit: I came up with this expression for picking up ASP.NET expressions: <%.+?%> then I found the one Microsoft made (the above full expression in question). I'm trying to understand why they chose that particular expression when mine seems a lot simpler. (I'm trying to see if my expression ignores certain boundary conditions that the MS one doesn't.)

like image 224
xxbbcc Avatar asked Dec 12 '25 12:12

xxbbcc


1 Answers

It's a negative lookahead assertion that matches if the next character is not # or $, but doesn't consume it.

It's very simlar to the negative character class [^#$] except that the negative character class also consumes the character, preventing it from being matched by the rest of the expression.

To see the difference consider matching <%test%>.

  • The expression <%(?![#$])(([^%]*)%)*?> captures test%. (rubular)
  • The expression <%[^#$](([^%]*)%)*?> captures est% because the t was consumed by the negative character class. (rubular)
like image 196
Mark Byers Avatar answered Dec 14 '25 03:12

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!