正则匹配
1,匹配标签里面的内容
StringBuilder sbStr = new StringBuilder();
sbStr.Append("<Head>");
sbStr.Append("\r\n ");
sbStr.Append("<Title>Ben Forta's HomePage</Title>");
sbStr.Append("\r\n");
sbStr.Append("</Head>");
string expression = @"(?<=<title>).*?(?=</title>)";
Regex reg = new Regex(expression, RegexOptions.IgnoreCase);
MatchCollection mc = reg.Matches(sbStr.ToString());
foreach (Match match in mc)
{
Console.WriteLine(match.Value);
}
Console.ReadKey();
2.匹配json
string str = "{\"row1\":[{\"YYYWBH\":\"030301030000001\",\"SLDW\":\"440309000000\",\"WSYYSJ\":\"2015-06-11 10:00-11:00\"},{\"YYYWBH\":\"030301030000001\",\"SLDW\":\"440309000000\",\"WSYYSJ\":\"2015-06-11 10:00-11:00\"}],\"returnCode\":\"1\",\"returnInfo\":\"\"}";
Regex regex = new Regex(@"""YYYWBH"":\s*""(?'YYYWBH'[^""]*)"",\s*""SLDW"":\s*(?'SLDW'[^,]*),\s*""WSYYSJ"":\s*(?'WSYYSJ'[^\}]*)", RegexOptions.IgnoreCase);
//申明和实例化一个正则表达式对象,这里要加上参数RegexOptions.IgnoreCase,用于忽略文本大小写
if (regex.IsMatch(str))
{
MatchCollection matches = regex.Matches(str);
//上处可以匹配文本里有多组相似的结果全部结果,如果只有一组的话,用Match match = regex.Match(json);
StringBuilder stringBuilder = new StringBuilder();
foreach (Match match in matches)
{
string name = match.Groups["YYYWBH"].Value;//此处Name是匹配表达式(?'Name'[^"]*)里的Name,显式分组
string age = match.Groups["SLDW"].Value;
string married = match.Groups["WSYYSJ"].Value;
stringBuilder.AppendFormat("YYYWBH:{0},SLDW:{1},WSYYSJ:{2}\n", name, age, married);
}
Console.WriteLine(stringBuilder.ToString());
}