Why does this regex with no special character match a longer string?

前端 未结 4 1030
有刺的猬
有刺的猬 2021-01-23 00:21

I am using this method to try find a match, in an example:

Regex.Match(\"A2-TS-OIL\", \"TS-OIL\", RegexOptions.IgnoreCase).Success;

I got a tru

相关标签:
4条回答
  • 2021-01-23 00:47

    TS-OIL is a substring in your A2-TS-OIL. So, it would generate a match. You have the simplest match possible - literal substring. If you want TS-OIL to not match, you could also try (?!^A2-)(TS-OIL), assuming that you don't want it to start with A2-, but other things might be desired.

    0 讨论(0)
  • 2021-01-23 00:52

    There's an implicit .* at the beginning and end of the expression string. You need to use ^ and $ which represent the start and end of the string to override that.

    0 讨论(0)
  • 2021-01-23 00:55

    A regex match doesn't have to start at begining of the input. You might want:

    ^TS-OIL
    

    if you want to only match at the start. Or:

    ^TS-OIL$
    

    to prevent it matching TS-OIL-123.

    ^ matches the start of the input, $ matches the end.

    I believe there are some place where the ^ and $ get added automatically (like web validation controls) but they're the exception.

    btw, you could use:

    Regex.IsMatch(...)
    

    in this case to save a few keystrokes.

    0 讨论(0)
  • 2021-01-23 00:56

    If you only want a match if the test string starts with your regular expression, then you need to indicate as such:

    Regex.Match("A2-TS-OIL", "^TS-OIL", RegexOptions.IgnoreCase).Success;
    

    The ^ indicates that the match must start at the beginning of the string.

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