基本用法
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