In C#, how to compare 2 strings, 1 of string had '*' / wildcard

103 Views Asked by At

How to compare two strings, one of which contains wildcard symbols? Like this:

string string1 = "/api/mymember/get";
# * is any text
string string2 = "/api/*/get";

I'd like a way to make string1 equal string2.

In C#, is the function regex.match able to do that? If string2 is a pattern.

Or I need custom a script to compare it?

2

There are 2 best solutions below

6
X3R0 On

Use regex.

You will also need to import the namespace for regex:

using System.Text.RegularExpressions;

Actual regex code requested:

string string1 = "/api/mymember/get";

// Regex
string string2regexPattern = "^/api/[^/]+/get$"; // Regex pattern for matching string

// Output
bool doesString1MatchPattern = Regex.IsMatch(string1, string2regexPattern);
0
Enigmativity On

Here's how to turn a * wildcard into valid Regex:

string string2 = "/api/*/get";
Regex regex = new Regex($"^{String.Join(".*", string2.Split('*').Select(x => Regex.Escape(x)))}$");

That produces ^/api/.*/get$ as the Regex. I anchored it to the start and the end of the string to make sure it matched everything.

string string1 = "/api/mymember/get";
Console.WriteLine(regex.IsMatch(string1));

That produces True to the console.