3

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.)

1
  • 1
    Regex: <%(?![#$])(([^%]*)%)*?> - the new APL: ⎕←{⍵⍨~{⍵∨≠\⍵}⍵∊'<>'}txt Commented Apr 27, 2012 at 6:40

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Mark, thanks for the answer. Is there an example that wouldn't match this regex? I'm asking because I'm trying to understand why this would be better than just using <%.+?%> instead. All examples I tried so far seem to match both the same way.
@xxbbcc: <%#thisshouldntmatch%>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.