关于C#中正则表达式的匹配

来源:百度知道 编辑:UC知道 时间:2024/06/11 01:08:15
先看我的例子哈
string testStr="<tr><td>this is the test!</td></tr>";
Regex r=new Regex("<td>.*?</td>");
string resultStr=r.Match(testStr).Vaue;
如上,这样取到的result值是:<td>this is the test!</td>,现在的问题是。我只想要我(.*?)这个的值,也就是:this is the test!,而不需要<td>和</td>,请问除了匹配后替换不需要的字符串外,还有没有别的办法?也就是匹配后的值只要我用了正则表达式元字符的数据。
谢谢大家了。。。

匹配表达式为:
(?<=<td>).+?(?=</td>)
如果是HTML文档,当正文中包含回车符时,可以使用:
(?<=<td>)(.|\n)+?(?=</td>)

希望对你有帮助

1.使用零宽断言(?=) 、(?<=)
2.把中间部分设置为捕获组

只需要这么写就行了 <td>(.*?)</td>

Regex r=new Regex("<td>.*?</td>");
把这句改一下
Regex r=new Regex("<td>(.*?)</td>");

然后使用 match.group数组就行了,具体的msdn里面写的很清楚

string testStr="<tr><td>this is the test!</td></tr>";
Regex r=new Regex("<tr><td>(.*?)</td></tr>");
string resultStr=r.Match(testStr).Vaue;