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
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.
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.
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.
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.