C#中正则表达式编程(未完,待补充)
2021-02-14 04:19
对于只存储一个匹配,可用Match类:
一般模式:
Regex reg = new Regex(string pattern);
string str = "###############";
Match ma = reg.Match(str);
确定是否成功,用 if(ma.Success)判断
也可以用 if(Regex.IsMatch(str,pattern))
================================================================
通用模式:
对于要存储多个匹配,可用MatchCollection类 对象存储 :(所以这个更通用,记住这个)
方式一:
Regex reg = new Regex(string pattern);
string str = "###############";
MatchCollection ma = reg.Matches(str);
方式二:
不再通过new Regex(string pattern);声明来传递正则表达式,而是直接
string str = "###############";
MatchCollection ma = Regex.Matches(str,pattern);
===========================================
另:对是否匹配上的判别,有通用的方式:
if (Regex.IsMatch(str, pattern))
========================
小例子:
class Program { static void Main(string[] args) { string pattern = @"ba{2}d"; string[] words = new string[]{"bad","boy","baad","baaad","bear","bend"}; //要遍历数组内每一个字符串,看那个可以匹配baad Regex regex = new Regex(pattern); foreach (string word in words) { if (Regex.IsMatch(word, pattern))//如果有匹配 { MatchCollection mat = regex.Matches(word); for (int i = 0; i ) { Console.WriteLine(mat[i].Value); } } } Console.ReadKey(); } }
下一篇:WPF 16进制byte输入框
文章标题:C#中正则表达式编程(未完,待补充)
文章链接:http://soscw.com/index.php/essay/55084.html