如何比较两个字符串,其中一个字符串包含通配符? 像这样:
string string1 = "/api/mymember/get";
# * is any text
string string2 = "/api/*/get";
我想要一种方法使
string1
等于 string2
。
在C#中,函数
regex.match
可以做到这一点吗?如果 string2
是一个模式。
或者我需要自定义脚本来比较它?
以下是如何将
*
通配符变为有效 Regex
:
string string2 = "/api/*/get";
Regex regex = new Regex($"^{String.Join(".*", string2.Split('*').Select(x => Regex.Escape(x)))}$");
生成
^/api/.*/get$
作为 Regex
。我将它锚定到字符串的开头和结尾,以确保它匹配所有内容。
string string1 = "/api/mymember/get";
Console.WriteLine(regex.IsMatch(string1));
这会在控制台产生
True
。
使用正则表达式。
您还需要导入正则表达式的命名空间:
using System.Text.RegularExpressions;
实际请求的正则表达式代码:
string string1 = "/api/mymember/get";
// Regex
string string2regexPattern = "^/api/[^/]+/get$"; // Regex pattern for matching string
// Output
bool doesString1MatchPattern = Regex.IsMatch(string1, string2regexPattern);