I've just started using Regular Expressions
and this is so overwhelming that even after reading documentation I can't seem to find where to start to help with my problem.
I have to a bunch of strings.
"Project1 - Notepad"
"Project2 - Notepad"
"Project3 - Notepad"
"Untitled - Notepad"
"HeyHo - Notepad"
And I have a string containing a wild card.
"* - Notepad"
I would need that if I compare any of these strings with the one containing the wildcard it returns true. (With Regex.IsMatch()
or something like that..)
I don't usually asks for answers like that but I just can't find what I need. Could someone just point me out in the right direction ?
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.
you can do either:
Regex.IsMatch(input, pattern);
or
var regex = new Regex(pattern);
regex.IsMatch(input);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With