//使用正则表达式匹配组
//需要引入命名空间using
System.Text.RegularExpressions;
string s =
"你是tom,我是jerry,他是韩梅梅,哈哈";
MatchCollection matches = Regex.Matches(s, @"是(\w+),");
//匹配组从0开始
for (int i = 0; i <
matches.Count; i++)
{
Match match =
matches[i];
//match.Value是匹配的内容
Console.WriteLine(match.Value);
string name =
match.Groups[1].Value;
Console.WriteLine(name);
}
//使用正则表达式提取字符串
string s = "老王的英文名字是Wrong";
Match match = Regex.Match(s,
@"^(\w+)的英文名字是(\w+)$");
//是否匹配成功
if
(match.Success)
{
//分组序号从1开始
string cnName =
match.Groups[1].Value;
string enName =
match.Groups[2].Value;
Console.WriteLine(cnName);
Console.WriteLine(enName);
}
string s = "June
26,
1951";
Match match = Regex.Match(s,
@"^([a-zA-Z]+)\s+\d{1,2},\s*\d{4}$");
if
(match.Success)
{
string month =
match.Groups[1].Value;
Console.WriteLine(month);
}
Match match =
Regex.Match("大家好。我是S.H.E。我22岁了。我病了,呜呜。fffff",
"我是(.+)。");//+、*是贪婪的,会一直向后匹配,直到再贪婪一下后续就无法匹配为止。
Match match =
Regex.Match("大家好。我是S.H.E。我22岁了。我病了,呜呜。fffff",
"我是(.+?)。");//+、*后加?表示“尽可能早的让后面的模式匹配”
if
(match.Success)
{
string name =
match.Groups[1].Value;
Console.WriteLine(name);
}
Console.ReadKey();
加载中,请稍候......