我需要比较两个字符串,其中一个使用“*”作为通配符。当我意识到 RegEx 可以更快地执行任务时,我正在考虑使用迭代或递归方法。不幸的是,我是 RegEx 的新手,不知道该怎么做。
如果我发送模式“He**o”,那么“Hello”和“He7(o”应该返回 true,但“Hhllo”应该返回 false。
最佳答案
假设您的意思是 *
是单字符通配符,则 Regex 模式中的正确替换是点 (.
):
string pattern = "He**o";
string regexPattern = pattern.Replace("*",".");
Regex.IsMatch("Hello",regexPattern); // true
Regex.IsMatch("He7)o",regexPattern); // true
Regex.IsMatch("he7)o",regexPattern); // false
Regex.IsMatch("he7)o",regexPattern, RegexOptions.IgnoreCase); // true
您可能还想使用 ^
(字符串开头)和 $
(字符串结尾)来锚定模式:
regexPattern = String.Format("^{0}$", pattern.Replace("*","."));
如果您希望它能够解析带有特殊字符的输入字符串,您可以像这样转义所有其他字符:
string regexPattern = String.Join(".",pattern.Split("*".ToCharArray())
.Select(s => Regex.Escape(s)).ToArray());
关于c# - 使用通配符比较两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33112162/