1、{n} 匹配前面的字符n次
string pattern = "x{2}";
string str = "jx0xxdxxxfxxxxg";
Regex regex = new Regex(pattern);
var collection = regex.Matches(str);
foreach (Match item in collection)
{
Console.WriteLine(item.Value);
}
输出:
xx
xx
xx
xx
从左往右找到xx然后就就接着找下一个xx
2、{n,} 匹配前面的字符n次或者更多
Console.WriteLine();
pattern = "x{2,}";
regex = new Regex(pattern);
collection = regex.Matches(str);
foreach (Match item in collection)
{
Console.WriteLine(item.Value);
}
输出:
xx
xxx
xxxx
找到两个连着的x,如果多于两个,则接着往后找一直到不是x。
3、{n,m} 匹配前面的字符最少n次,最多m次,n也可以为0
Console.WriteLine();
pattern = "x{0,2}";
regex = new Regex(pattern);
collection = regex.Matches(str);
foreach (Match item in collection)
{
Console.WriteLine(item.Value==""?"空":item.Value );
}
Console.WriteLine();
pattern = "x{2,3}";
regex = new Regex(pattern);
collection = regex.Matches(str);
foreach (Match item in collection)
{
Console.WriteLine(item.Value);
}
输出:
空
x
空
xx
空
xx
x
空
xx
xx
空
空
xx
xxx
xxx
找至少2个x,最多3个x,找完了最多3个x后,然后就接着找下一个最多3个x的匹配
4、? 匹配前面的字符0次或1次
Console.WriteLine();
pattern = "x?";
regex = new Regex(pattern);
collection = regex.Matches(str);
foreach (Match item in collection)
{
Console.WriteLine(item.Value == "" ? "空" : item.Value);
}
5、+ 匹配前面的字符1次或多次
Console.WriteLine();
pattern = "x?";
regex = new Regex(pattern);
collection = regex.Matches(str);
foreach (Match item in collection)
{
Console.WriteLine(item.Value == "" ? "空" : item.Value);
}
输出:
空
x
空
x
x
空
x
x
x
空
x
x
x
x
空
空
6、*匹配前面的字符0次或多次
Console.WriteLine();
pattern = "x*";
regex = new Regex(pattern);
collection = regex.Matches(str);
foreach (Match item in collection)
{
Console.WriteLine(item.Value == "" ? "空" : item.Value);
}
空
x
空
xx
空
xxx
空
xxxx
空
空
这里比较奇怪的是,最后有两个空,难道不应该是一个空吗?就是末尾的字符g不太符合。