C#正则表达式Regex类的使用

using System.Text.RegularExpressions;
namespace 测试控制台
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "666";
            string str3 = "101,102,103,104$";
            string par = @"\d{3,4}";
            string par3 = @"[,]";
            string par4 = @"\d+";
            // 一,常用方法:
            //1.IsMatch判断是否为(3到4位的数字)
            bool b = Regex.IsMatch(str, par);
            //2.Matches可计算匹配到的个数
            int i3= Regex.Matches(str3, par3).Count;
            //3.Match 返回第一个匹配项
            string s4 = Regex.Match(str3, par4).Value;//或者Regex.Match(str3, par4).ToString();
            // 二,RegEx类的实例
            // 1,替换
            string c=Regex.Replace("1人做事1人当", @"\d", "2");
            string c8 = "one two";
            string js = Regex.Replace(c8, @"(\w+)(\s)(\w+)", @"$3$2$1");//替换
            string js2 = Regex.Replace(c8, @"(?<w1>\w+)(\s)(?<w2>\w+)", @"${w2} ${w1}");//命名替换
            // str.Replace("\", "\\")用于简单的替换
            string s20="1人做事1人当";
            string s21 = s20.Replace("1", "2");
            // 2,取值 利用小括号()分组
            string line = "lane=1;speed=30.3mph;speed=32.2m/s;acceleration=2.5mph/s";
            MatchCollection matches = Regex.Matches(line, @"speed=([\d\.]+)(m/s|mph)");
            string a1 = matches[0].Groups[1].Value;//30.3
            string a2 = matches[0].Groups[2].Value;//mph
            string b1 = matches[1].Groups[1].Value;//32.2
            string b2 = matches[1].Groups[2].Value;//m/s
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值