C#正则表达式解析模版列表标签,在线等求解

ericSola 2011-05-03 11:14:34
这是一段解析的代码

public void Tag_ImgList()
{
string html = this.GetText();
StringBuilder sb = new StringBuilder();

string reg = "{fortyps:imglist(\\s+)(?<attr>[\\s\\S]*)}(?<content>[\\s\\S]*){/fortyps:imglist}";
MatchCollection matches = Regex.Matches(html, reg);
foreach (Match match in matches)
{
GroupCollection groups = match.Groups;
string attr = groups["attr"].Value;
string content = groups["content"].Value;
string value = match.Value;

string typeid = fortyps.util.Text.getAttributeValue(attr, "typeid");
string total = fortyps.util.Text.getAttributeValue(attr, "total");

this.elements.Add("a", typeid);
this.elements.Add("b", total);
}
}


这是 fortyps.util.Text.getAttributeValue 方法

public static string getAttributeValue(string s, string name)
{
string reg = name + "=\"(?<val>.*?)\"";
MatchCollection matches = Regex.Matches(s, reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
foreach (Match match in matches)
{
return match.Groups["val"].Value;
}
return string.Empty;
}


其他的方法 例如:GetText只是获取模版内容,elements.Add 是把解析的值输出来
-----------------

现在的问题是,如果模版中只有一个imglist标签就可以解析成功
当有两个或两个以上的时候就会解析失败
模版中是这么写的

{fortyps:imglist typeid="4" total="11"}
fsadfdsfdsf
{/fortyps:imglist}
...全文
177 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
ericSola 2011-05-04
  • 打赏
  • 举报
回复
解决了
这样写就行了

{fortyps:imglist(.*)}([\\s\\S]*?){/fortyps:imglist}
ericSola 2011-05-03
  • 打赏
  • 举报
回复
一个标签时 matches.count = 1
多个标签时 matches.count 也等于 1
应该是正则表达式有问题
ericSola 2011-05-03
  • 打赏
  • 举报
回复
一个标签时 matches.count = 1
多个标签时 matches.count = 1
应该是我的正则表达式写错了

一个时

{fortyps:imglist typeid="4" total="11"}
fsadfdsfdsf
{/fortyps:imglist}



多个时

{fortyps:imglist typeid="4" total="11"}
fsadfdsfdsf
{/fortyps:imglist}

{fortyps:imglist typeid="2" total="11"}
fsadfdsfdsf
{/fortyps:imglist}


{fortyps:imglist typeid="1" total="11"}
fsadfdsfdsf
{/fortyps:imglist}


{fortyps:imglist typeid="3" total="11"}
fsadfdsfdsf
{/fortyps:imglist}


kingdom_0 2011-05-03
  • 打赏
  • 举报
回复
foreach 处设置断点,看看你regex出的结果是什么样儿的,之后改进
ericSola 2011-05-03
  • 打赏
  • 举报
回复
回答一下吧
ericSola 2011-05-03
  • 打赏
  • 举报
回复
kinddom, thanks
kingdom_0 2011-05-03
  • 打赏
  • 举报
回复

111,092

社区成员

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

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

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