我需要比较两个字符串,其中一个使用“*”作为通配符。我想使用迭代或递归方法,但后来意识到正则表达式会更快地执行任务。不幸的是,我对正则表达式还不熟悉,不知道该怎么做。
如果我输入模式“He**o”,那么“Hello”和“He7(o”应该返回true,但“Hhllo”应该返回false。
*
作为单个字符通配符,那么在正则表达式模式中使用正确的替换是点号 (.
):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());
使用for循环中的char索引比较字符串。如果出现模式字符(通配符),则忽略比较并继续进行下一个比较。
private bool Compare(string pattern, string compare)
{
if (pattern.Length != compare.Length)
//strings don't match
return false;
for(int x = 0, x < pattern.Length, x++)
{
if (pattern[x] != '*')
{
if (pattern[x] != compare[x])
return false;
}
}
return true;
}
使用“He..lo”创建正则表达式
这是一个不会被识别的情况。
Regex r = new Regex("He..o");
string test = "Hhleo";
bool sucess = r.Match(a).Success;
Regex r = new Regex("He..o");
string test = "He7)o";
bool sucess = r.Match(a).Success;
这正是我今天在php
中所做的。当你添加了这个:
if (pattern[x] != '*' && compare[x] != '*')
&&
表示逻辑与,就像在php
中一样)
He..o
。点号表示任意字符。 - user4227915