Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match an entire string with a regex?

Tags:

c#

.net

regex

I need a regex that will only find matches where the entire string matches my query.

For instance if I do a search for movies with the name "Red October" I only want to match on that exact title (case insensitive) but not match titles like "The Hunt For Red October". Not quite sure I know how to do this. Anyone know?

Thanks!

like image 844
Micah Avatar asked Nov 08 '10 11:11

Micah


2 Answers

Try the following regular expression:

^Red October$ 

By default, regular expressions are case sensitive. The ^ marks the start of the matching text and $ the end.

like image 146
Pieter van Ginkel Avatar answered Sep 23 '22 17:09

Pieter van Ginkel


Generally, and with default settings, ^ and $ anchors are a good way of ensuring that a regex matches an entire string.

A few caveats, though:

If you have alternation in your regex, be sure to enclose your regex in a non-capturing group before surrounding it with ^ and $:

^foo|bar$ 

is of course different from

^(?:foo|bar)$ 

Also, ^ and $ can take on a different meaning (start/end of line instead of start/end of string) if certain options are set. In text editors that support regular expressions, this is usually the default behaviour. In some languages, especially Ruby, this behaviour cannot even be switched off.

Therefore there is another set of anchors that are guaranteed to only match at the start/end of the entire string:

\A matches at the start of the string.

\Z matches at the end of the string or before a final line break.

\z matches at the very end of the string.

But not all languages support these anchors, most notably JavaScript.

like image 42
Tim Pietzcker Avatar answered Sep 22 '22 17:09

Tim Pietzcker