How do I match an entire string with a regex?

前端 未结 7 1173
渐次进展
渐次进展 2020-11-22 00:15

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 wa

相关标签:
7条回答
  • 2020-11-22 00:28

    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
    }
    
    0 讨论(0)
  • 2020-11-22 00:31

    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());
    
    0 讨论(0)
  • 2020-11-22 00:31

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

    0 讨论(0)
  • 2020-11-22 00:32

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

    ^Red October$
    
    0 讨论(0)
  • 2020-11-22 00:35

    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
    
    0 讨论(0)
  • 2020-11-22 00:38

    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.

    0 讨论(0)
提交回复
热议问题