需要执行通配符(*,?等)搜索使用正则表达式的字符串通配符、字符串、正则表达式

2023-09-02 11:47:55 作者:我是纯情小骚货

我需要执行通配符( * 等)搜索的字符串。 这是我做了什么:

I need to perform Wildcard (*, ?, etc.) search on a string. This is what I have done:

string input = "Message";
string pattern = "d*";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

if (regex.IsMatch(input))
{
    MessageBox.Show("Found");
}
else
{
    MessageBox.Show("Not Found");
}

通过上面的code找到块击中,但实际上它不应该!

With the above code "Found" block is hitting but actually it should not!

如果我的模式是E *则只有发现应该打。

If my pattern is "e*" then only "Found" should hit.

我的理解或要求D *搜索应该查找包含后跟任意字符的文本D。

My understanding or requirement is d* search should find the text containing "d" followed by any characters.

我应该改变我的模式为D。*和e。*?是否有任何的.NET支持外卡同时使用正则表达式类,它内部是不是?

Should I change my pattern as "d.*" and "e.*"? Is there any support in .NET for Wild Card which internally does it while using Regex class?

推荐答案

这不是很难。从http://www.$c$cproject.com/KB/recipes/wildcardtoregex.aspx:

public static string WildcardToRegex(string pattern)
{
    return "^" + Regex.Escape(pattern)
                      .Replace(@"*", ".*")
                      .Replace(@"?", ".")
               + "$";
}

因此​​,像富的* .xls?将得到转化为 ^富。* 。xls的。$