tags:

views:

153

answers:

4

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? Thanks!

+10  A: 

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.

^ represnts the start of the input, $ represent 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 keystrokds.

it depends
+1  A: 

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.

Welbog
+4  A: 

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.

Andy
+1  A: 

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.

Bill Perkins
Not quite. The regex for "contains TS-OIL and doesn't start with A2-" would be "^(?!A2-).*TS-OIL" or "(?<!^A2-)TS-OIL". But I think the OP was just expecting "TS-OIL" to act like "^TS-OIL$".
Alan Moore