Reputation: 38664
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 true result. I am confused. I think this should return false since there is no special characters in the pattern. If I use ".+TS-OIL"
, true should be returned (.
for any and +
for more than 1). How should I do to get what I need?
Upvotes: 2
Views: 321
Reputation: 7543
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.
Upvotes: 11
Reputation: 204
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.
Upvotes: 0
Reputation: 30418
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.
Upvotes: 5
Reputation: 60438
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.
Upvotes: 1