How do I match an entire string with a regex?

2018-12-31 05:44发布

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!

标签: c# .net regex
8条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 05:44

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.

查看更多
若你有天会懂
3楼-- · 2018-12-31 05:45

Matching the entire string can be done with ^ and $ as said in previous answers.

To make the regex case insensitive, you can implement a hack that involves character classes. A lot of character classes.

^[Rr][Ee][Dd] [Oo][Cc][Tt][Oo][Bb][Ee][Rr]$
查看更多
不再属于我。
4楼-- · 2018-12-31 05:48

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
}
查看更多
骚的不知所云
5楼-- · 2018-12-31 05:53

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]$

查看更多
高级女魔头
6楼-- · 2018-12-31 06:00

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

^Red October$
查看更多
宁负流年不负卿
7楼-- · 2018-12-31 06:03

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
查看更多
登录 后发表回答