字符串一:
<title>AAAA</title>
<desc>BBBB</desc>
<surl>CCCC</surl>
<curl>DDDD</curl> 字符串二:
<title>AAAA</title>
<curl>DDDD</curl>
我想匹配出上面两个字符串中的“AAAA”和“DDDD”,也就是<title>和<curl>对应的内容,请问用什么一个什么样的正则表达式,既可以匹配字符串一,也可以匹配出字符串二中的相关内容?
<title>AAAA</title>
<desc>BBBB</desc>
<surl>CCCC</surl>
<curl>DDDD</curl> 字符串二:
<title>AAAA</title>
<curl>DDDD</curl>
我想匹配出上面两个字符串中的“AAAA”和“DDDD”,也就是<title>和<curl>对应的内容,请问用什么一个什么样的正则表达式,既可以匹配字符串一,也可以匹配出字符串二中的相关内容?
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;namespace ConsoleApplication6
{ internal class Program
{
private static void Main(string[] args)
{
string str1 =
@"<title>AAAA </title>
<desc>BBBB </desc>
<surl>CCCC </surl>
<curl>DDDD </curl>";
string str2 =
@"<title>AAAA </title>
<curl>DDDD </curl>";
Regex regex = new Regex(@"(<title>(?<title>[\w\s]+)</title>)[\w</>\s\n]*(<curl>(?<curl>[\w\s]+)</curl>)");
if(regex.IsMatch(str1))
{
Console.WriteLine(regex.Match(str1).Groups["title"]);
Console.WriteLine(regex.Match(str1).Groups["curl"]);
} if(regex.IsMatch(str2))
{
Console.WriteLine(regex.Match(str1).Groups["title"]);
Console.WriteLine(regex.Match(str1).Groups["curl"]);
}
Console.ReadLine();
}
}
}
最常规的写法
Match m = Regex.Match(yourStr, @"<title>(?<title>[\s\S]*?)</title>[\s\S]*?<curl>(?<curl>[\s\S]*?)</curl>", RegexOptions.IgnoreCase);
if(m.Success)
{
richTextBox2.Text += m.Groups["title"].Value + "\n";
richTextBox2.Text += m.Groups["curl"].Value + "\n";
}