C#字符串与通配符匹配 [英] C# string matching with wildcards
本文介绍了C#字符串与通配符匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C#如何与通配符匹配字符串?通配符有两个标记,问题和星号。 ?表示任意字符,*表示任意字符。如何通过使用C#来实现此功能。谢谢。
C# how to achive string matching with wildcards?Wildcards there are two marks, question and asterisks. "?" Represents an arbitrary character, and "*" indicates that any arbitrary character.How to achive this function by use C#.Thank you.
推荐答案
请查看以下提示(不要把它当作文章,尽管如此分类):将通配符转换为正则表达式 [< a href =http://www.codeproject.com/Articles/11556/Converting-Wildcards-to-Regexestarget =_ blanktitle =New Window> ^ ]
Look at the following tip (do not consider it an article, although so classified): Converting Wildcards to Regexes[^]
学习regexp:
30分钟正则表达式教程 [ ^ ]
现在使用w +等在*等正则表达式替换字符串
Learn regexp:
The 30 Minute Regex Tutorial[^]
Now do some string replacement on regex like * with w+ etc
尝试以下代码
try below code
public static class WildcardMatch
{
#region Public Methods
public static bool IsLike(string pattern, string text, bool caseSensitive=false)
{
pattern = pattern.Replace(".", @"\.");
pattern = pattern.Replace("?", ".");
pattern = pattern.Replace("*", ".*?");
pattern = pattern.Replace(@"\", @"\\");
pattern = pattern.Replace(" ", @"\s");
return new Regex(pattern, caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase).IsMatch(text);
}
#endregion
}
这篇关于C#字符串与通配符匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文