需要执行通配符(*,?等)搜索使用正则表达式的字符串 [英] Need to perform Wildcard (*,?, etc) search on a string using Regex

查看:288
本文介绍了需要执行通配符(*,?等)搜索使用正则表达式的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

这不是很难。从<一个href="http://www.$c$cproject.com/KB/recipes/wildcardtoregex.aspx">http://www.$c$cproject.com/KB/recipes/wildcardtoregex.aspx:

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

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

这篇关于需要执行通配符(*,?等)搜索使用正则表达式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆