不好意思,每次发问题都很少人问个正则表达式的问题取值的问题
像取值
一个标题一个内容
<title>7899</title>
html代码很多《body><table>
<content>99999999999</content>
我怎么样能一块取到标题和内容
这个正则怎么些
像取值
一个标题一个内容
<title>7899</title>
html代码很多《body><table>
<content>99999999999</content>
我怎么样能一块取到标题和内容
这个正则怎么些
<title.*?>([\s\S]*?)</title[\s\S]*?<body.*?>([\s\S]*)</body
<html>
<head>
<title>aaaa</title>
<body>
bbbbb
</body>
</html>
";
Regex reg = new Regex(@"<title.*?>([\s\S]*?) </title[\s\S]*? <body.*?>([\s\S]*) </body", RegexOptions.IgnoreCase);
Match match = reg.Match(html);
if(match.Success){
string title = match.Result("$1");// 这是取得的标题
string body = match.Result("$2");// 这是取得的内容
}
<html>
<head>
<title>aaaa</title>
<body>
bbbbb
</body>
</html>
";
Regex reg = new Regex(@"<title.*?>([\s\S]*?)</title[\s\S]*?<body.*?>([\s\S]*)</body", RegexOptions.IgnoreCase);
Match match = reg.Match(html);
if (match.Success)
{
string title = match.Result("$1");// 这是取得的标题
MessageBox.Show(title);
string body = match.Result("$2");// 这是取得的内容
MessageBox.Show(body);
}
正则如下<(?<tag>(?=title|content)[^>]*)>(?<value>[^<]*)</\k<tag>>C#using System.Text.RegularExpressions; //先引用正则的命名空间private static string patternRegion = @"\<(?<tag>(?=title|content)[^>]*)>(?<value>[^<]*)</\k<tag>>";
private static readonly RegexOptions regexOptions = RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled;Regex regexRegion = new Regex(patternRegion, regexOptions); //解析Region的正则MatchCollection mc = regexRegion.Matches(code); //code为要分析的网页代码
foreach(Match m in mc)
{
string strtag= m.Groups["tag"].Value;//取匹配到的命名组的值
string strTitle=string.Empty;
string strContent=string.Empty;
if (strtag.ToLower()=="title")
{
strTitle=m.Groups["value"].Value;
}
else if (strtag.ToLower()=="content")
{
strContent=m.Groups["value"].Value;
}}仅供参考