The wildcard *
is equivalent to the Regex pattern ".*"
(greedy) or ".*?"
(not-greedy), so you'll want to perform a string.Replace()
:
string pattern = Regex.Escape(inputPattern).Replace("\\*", ".*?");
Note the Regex.Escape(inputPattern)
at the beginning. Since inputPattern
may contain special characters used by Regex, you need to properly escape those characters. If you don't, your pattern would explode.
Regex.IsMatch(input, ".NET"); // may match ".NET", "aNET", "FNET", "7NET" and many more
As a result, the wildcard *
is escaped to \\*
, which is why we replace the escaped wildcard rather than just the wildcard itself.
To use the pattern
you can do either:
Regex.IsMatch(input, pattern);
or
var regex = new Regex(pattern);
regex.IsMatch(input);
Difference between greedy and not-greedy
The difference is in how much the pattern will try to match.
Consider the following string: "hello (x+1)(x-1) world"
. You want to match the opening bracket (
and the closing bracket )
as well as anything in-between.
Greedy would match only "(x+1)(x-1)"
and nothing else. It basically matches the longest substring it can find.
Not-greedy would match "(x+1)"
and "(x-1)"
and nothing else. In other words: the shortest substrings possible.