Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Regexs only match on exact-matches?

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?

like image 825
Earlz Avatar asked Jan 03 '11 00:01

Earlz


People also ask

How do you match exact strings?

But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.

How do I match a specific character in regex?

Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

How do you match a specific sentence in regex?

Example is: string pattern = @"(Band) (? <Band>[A-Za-z ]+) (? <City>@[A-Za-z ]+) (?

What does * do in regex?

This operator is similar to the match-zero-or-more operator except that it repeats the preceding regular expression at least once; see section The Match-zero-or-more Operator ( * ), for what it operates on, how some syntax bits affect it, and how Regex backtracks to match it.


1 Answers

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

like image 192
ulrichb Avatar answered Sep 19 '22 13:09

ulrichb