102

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!

Micah
  • 111,873
  • 86
  • 233
  • 325
  • 1
    Why do you need a regex for something that a simple `string.Contains` will work for? – Oded Nov 08 '10 at 11:50
  • 1
    The reason I need to use a regex is that I'm using it for a search in MongoDB and I need to it to be case insensitive which can only be done with a regex – Micah Nov 08 '10 at 12:01
  • Why not convert (on-fly) db data to lowercase and user lower case string for search? – greenoldman Nov 08 '10 at 12:21
  • 1
    @macias I don't disagree that it would be a better option, but unfortunately my current situation does not allow it. – Micah Nov 08 '10 at 13:40
  • 2
    FYI, If don't require using a regex, just trying to compare two strings ignoring case, can simply do `string1.Equals(string2, StringComparison.OrdinalIgnoreCase);` – ToolmakerSteve Jan 12 '19 at 22:45

8 Answers8

135

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.

Pieter van Ginkel
  • 29,160
  • 8
  • 71
  • 111
  • 1
    FYI, worth mentioning that to make it case insensitive, when create regex object, add second parameter RegexOptions.IgnoreCase. – ToolmakerSteve Jan 12 '19 at 22:52
  • This fails to work if there is anything else surrounding that string. For example if you were searching for "St" as in Street, but you have other strings on the same line that also begin with "St" such as the name "Stirling" this regex will not do exact match. I am not sure RegEx is the right answer for this scenario unfortunately. I am going to keep trying though. Tim's answer below is good, but not all engines support this. – dyslexicanaboko Nov 02 '20 at 00:03
  • Actually, `$` does not always match the end of string, `\z` does (`\Z` is the equivalent in Python). Please see [Tim Pietzcker's answer](https://stackoverflow.com/a/4123738/3832970). It is true for JavaScript though. – Wiktor Stribiżew Nov 11 '20 at 23:14
51

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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 4
    this is the most helpful answer – Jeremy Danyow Jan 23 '15 at 14:18
  • An interesting point I didn't realize until researching it as a result of seeing it here: `?:` signifies that the brackets don't count as a capturing group (so they won't affect any existing group numbers in the existing REGEX). Just in case the flavour of REGEX you're using doesn't support this, you can alternatively use a look-behind and look-ahead (also non-capturing): `(?<=^)foo|bar(?=$)`. – Matt Arnold Mar 03 '21 at 17:00
24

I know that this may be a little late to answer this, but maybe it will come handy for someone else.

Simplest way:

var someString = "...";
var someRegex = "...";
var match = Regex.Match(someString , someRegex );
if(match.Success && match.Value.Length == someString.Length){
    //pass
} else {
    //fail
}
Zixav
  • 241
  • 2
  • 2
  • 2
    IMHO this is LESS simple than the accepted answer. But it is an alternative. – ToolmakerSteve Jan 12 '19 at 22:46
  • I like this answer because the code itself shows the intended behavior, rather than modifying the regex (which might be less clear to someone glancing at the code with little understanding of regex). The potential hiccup is that the regex could be written so that it could either match the entire string or a part of it, with the Regex.Match function returning the partial match even though a complete match is possible. – John Thoits Jul 13 '20 at 18:05
22

Use the ^ and $ modifiers to denote where the regex pattern sits relative to the start and end of the string:

Regex.Match("Red October", "^Red October$"); // pass
Regex.Match("The Hunt for Red October", "^Red October$"); // fail
Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
9

You need to enclose your regex in ^ (start of string) and $ (end of string):

^Red October$
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
1

If the string may contain regex metasymbols (. { } ( ) $ etc), I propose to use

^\QYourString\E$

\Q starts quoting all the characters until \E. Otherwise the regex can be unappropriate or even invalid. If the language uses regex as string parameter (as I see in the example), double slash should be used:

^\\QYourString\\E$

Hope this tip helps somebody.

demitt
  • 91
  • 2
  • 5
-2

Sorry, but that's a little unclear.

From what i read, you want to do simple string compare. You don't need regex for that.

string myTest = "Red October";
bool isMatch = (myTest.ToLower() == "Red October".ToLower());
Console.WriteLine(isMatch);
isMatch = (myTest.ToLower() == "The Hunt for Red October".ToLower());
Dean Thomas
  • 1,096
  • 1
  • 10
  • 25
  • 2
    The reason I need to use a regex is that I'm using it for a search in MongoDB and I need to it to be case insensitive wich can only be done with a regex. – Micah Nov 08 '10 at 11:52
-2

You can do it like this Exemple if i only want to catch one time the letter minus a in a string and it can be check with myRegex.IsMatch()

^[^e][e]{1}[^e]$