c#正则表达式——指定重复的字符

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不太符合。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

c#上位机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值