如何匹配这个正则表达式

honpher 2009-04-22 04:52:49
字符串一:
<title>AAAA</title>
<desc>BBBB</desc>
<surl>CCCC</surl>
<curl>DDDD</curl>

字符串二:
<title>AAAA</title>
<curl>DDDD</curl>


我想匹配出上面两个字符串中的“AAAA”和“DDDD”,也就是<title>和<curl>对应的内容,请问用什么一个什么样的正则表达式,既可以匹配字符串一,也可以匹配出字符串二中的相关内容?
...全文
52 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
honpher 2009-04-28
  • 打赏
  • 举报
回复
多谢,我验证一下。非常感谢楼上二位。
-过客- 2009-04-22
  • 打赏
  • 举报
回复
try...
最常规的写法
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";
}
cppfaq 2009-04-22
  • 打赏
  • 举报
回复
using System;
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();
}
}
}
honpher 2009-04-22
  • 打赏
  • 举报
回复
请问用什么一个什么样的正则表达式,既可以匹配字符串一,也可以匹配出字符串二中的相关内容?
cuisea 2009-04-22
  • 打赏
  • 举报
回复
看不懂你意思,正则表达式好像是对数据有效性进行验证吧。

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧