c# 正则表达式regex匹配

基本用法

Regex emailregex = new Regex("(?<user>[^@]+)@(?<host>[a-zA-Z]+).(?<net>[a-zA-Z]+)");

String s = "johndoe@tempuri.org";

Match m = emailregex.Match(s);

if (m.Success)
{
    Console.WriteLine("User: " + m.Groups["user"].Value);
    Console.WriteLine("Host: " + m.Groups["host"].Value);
    foreach (var bo in m.Groups)
    {
        Console.WriteLine(bo);
    }
}
else
{
    Console.WriteLine(s + " is not a valid email address");
}
Console.WriteLine();

输出

User: johndoe
Host: tempuri
johndoe@tempuri.org
johndoe
tempuri
org

多次匹配

var ati = "354cfvbdSDAS(){}][]D123123{ \"$numberInt\" : \"27\" }123{ \"$numberInt\" : \"32\" }";
var everyregex=new Regex(@"{ ""\$(?<str>[a-zA-Z]+)"" : ""(?<num>[0-9]+)"" }");

var mm=everyregex.Match(ati);
var mg = everyregex.Matches(ati);
Console.WriteLine(mg);
Console.WriteLine(mg.Count);
Console.WriteLine(mg.ToArray());
foreach (var b in mg.ToArray())
{
    Console.WriteLine(b);
    if(b.Success)
    {
        foreach (var bo in b.Groups)
        {
            Console.WriteLine(bo);
        }
    }
}

输出

System.Text.RegularExpressions.MatchCollection
2
System.Text.RegularExpressions.Match[]
{ "$numberInt" : "27" }
{ "$numberInt" : "27" }
numberInt
27
{ "$numberInt" : "32" }
{ "$numberInt" : "32" }
numberInt
32

正则替换

var ati = "354cfvbdSDAS(){}][]D123123{ \"$numberInt\" : \"27\" }123{ \"$numberInt\" : \"32\" }";
var everyregex = new Regex(@"{ ""\$(?<str>[a-zA-Z]+)"" : ""(?<num>[0-9]+)"" }");
Console.WriteLine(everyregex.Replace(ati, "中午"));

输出

354cfvbdSDAS(){}][]D123123中午123中午

把匹配的存进变量

var ati = "354cfvbdSDAS(){}][]D123123{ \"$numberInt\" : \"27\" }123{ \"$numberInt\" : \"32\" }";
var everyregex = new Regex(@"(?<num>[0-9]+)");
var mg = everyregex.Matches(ati);
foreach (var b in mg.ToArray())
{
    if (b.Success)
    {
        Console.WriteLine("num : "+ b.Groups["num"]);
    }
}

输出

num : 354
num : 123123
num : 27
num : 123
num : 32

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值