Nicholas Magnussen
Nicholas Magnussen

Reputation: 769

Regex - Match pattern A unless it matches pattern B

I'm trying to excluded some very specific routes from my MVC project. More specifically I want to ignore all calls to .ashx pages, unless they match a certain pattern.

(?<!invoices\/(order|membership)\/(\d{5,})-([a-f0-9]{8}))\.ashx

This is the pattern I came up with, but since you can't use quantifiers in a negated lookbehind, it's not working.

Any ideas as to how I can achieve this so I can ignore my routes correctly with a call like this:

routes.Ignore("{*handlers}", new { handlers = "(?<!invoices/(order|membership)/(\\d{5,})-([a-f0-9]{8}))\\.ashx" });

Upvotes: 1

Views: 120

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

.NET regex flavor does support infinite-width lookbehinds, so the only issue with your pattern is the double backslashes. Use \d instead of \\d and \. instead of \\., or just work around that with character classes [0-9] (a digit) and [.] (a literal dot):

(?<!invoices/(order|membership)/[0-9]{5,}-[a-f0-9]{8})[.]ashx
                                ^^^^^                 ^^^

You can also get rid of the lookbehind, and use a lookahead anchored at the start:

^(?!.*invoices/(order|membership)/[0-9]{5,}-[a-f0-9]{8}).*[.]ashx.

The (?!.*invoices/(order|membership)/[0-9]{5,}-[a-f0-9]{8}) negative lookahead will fail the match if a string contains (remove the first .* to make it starts with) the invoices/(order|membership)/[0-9]{5,}-[a-f0-9]{8} pattern.

Upvotes: 1

Related Questions