20

Ok, so basically I have some bit of code that matches URLs by regexs. It then will call some function based on which regex the URL matches against. I never want for more than one function to be called for a URL and I want the regex matches to have to be "exact"

For instance, with the simple URL / I use a simple regex / which will match / but it will also match things like /foo and /foo/bar.

How can I prevent this partial matching behavior in C#/.Net?

Earlz
  • 62,085
  • 98
  • 303
  • 499
  • 1
    Have you tried using .NET URL Routing instead of rolling your own route dispatcher? – Jacob Krall Jan 03 '11 at 03:32
  • 1
    @JacobKrall funny you should have mentioned that. I went on to implement my own URL routing(in a much more standalone fashion than .Net's) method like a month after this question :P – Earlz Feb 10 '12 at 21:52

2 Answers2

41

Use ^ for matching the start of a string and $ for the end of a string.

For example: ^/$ matches / but not /foo. And ^/ matches /foo but not foo/.

ulrichb
  • 19,610
  • 8
  • 73
  • 87
  • Hmm. I had to change around a few regexs to work with this, but this seems to be the answer. I wasn't sure it was possible to do this only be slightly modifying the regular expressions – Earlz Jan 03 '11 at 01:07
-3

Append space at start and end of keyword you want to match with. For example you have a string "Hey! foobar I am foo bar." Now lets say you want to match foo. You can do this /\s+foo\s+/i this will return match for only foo and not foobar.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 2
    This doesn't work if the word is the first the string or last in a sentence or the string. – Mat Nov 07 '11 at 13:56