日期:2014-05-16  浏览次数:20765 次

我这个正则匹配能不能再简单点?

'HtmlContent 是包含整个页面内容的变量
'{ArticleClass:li,li}是标签
'ArticleClass(HtmlStart,HtmlEnd)是一个已经经过各种处理的函数
'*******************************************
'匹配文章分类标签
'*******************************************
If instr(1,HtmlContent,"{ArticleClass:",1)>0 Then
    Set re=new RegExp
    re.IgnoreCase=True
    re.Global=True
    re.Pattern="\{ArticleClass\:(.*?),(.*?)\}"
    Set matches=re.Execute(HtmlContent)
    For each match in matches
        HtmlStart=match.submatches(0)
        HtmlEnd=match.submatches(1)
    ArticleClassStr=ArticleClass(HtmlStart,HtmlEnd)
    HtmlContent=Replace(HtmlContent,"{ArticleClass:"&HtmlStart&","&HtmlEnd&"}",ArticleClassStr)
    Next
End If
'*******************************************
'匹配文章列表标签
'*******************************************
If instr(1,HtmlContent,"{ArticleList:",1)>0 Then
    Set re=new RegExp
    re.IgnoreCase=True
    re.Global=True
    re.Pattern="\{ArticleList\:(.*?),(.*?),(.*?),(.*?),(.*?)\}"
    Set matches=re.Execute(HtmlContent)
    For each match in matches
        ClassType=match.submatches(0)
        Rows=match.submatches(1)
        HtmlStart=match.submatches(2)
        HtmlEnd=match.submatches(3)
        TimeStr=match.submatches(4)
    ArticleListStr=ArticleList(ClassType,Rows,HtmlStart,HtmlEnd,TimeStr)
    HtmlContent=(replace(HtmlContent,"{ArticleList:"&ClassType&","&Rows&","&HtmlStart&","&HtmlEnd&","&TimeStr&"}",ArticleListStr))
    Next
End If

我想把代码简化一下,因为我需要匹配的标签实在太多了,产品标签 产品分类等等太多了,像现在这样写肯定太那什么看,我不太会用正则,只能像现在这样用了,应该可以简化的吧,希望各位指点指点。
------解决方案--------------------
每个标签,处理方式都不一样,数据读取,字段等,都不一样,没办法写成一个统一函数。

要简化,也只能把标签读取这一块封装一下。简化这一块的内容。其它的地方,没办法简化。
------解决方案--------------------
Function ArticleClass(a,b,c)
ArticleClass="返回结果:"&a&b&c
End Function
Function ArticleList(a,b,c,d,e)
ArticleList="返回结果:"&a&b&c&d&e
End Function

Dim str,oExp,Matches,Match,fun
str="aabc<p>sdf{ArticleClass:23,""ab"",4}</p>sdfsdfs{ArticleList:4,""s"",232,""s"",2}sdfsdf"
Set oExp = New Regexp
oExp.IgnoreCase = True
oExp.Global = True
oExp.Pattern = "\{([a-z_]+):(([a-z0-9\""]+,?)+)\}"
Set Matches =oExp.Execute(str)
For Each Match in Matches
If InStr("ArticleClass
------解决方案--------------------
ArticleList",Match.submatches(0))<>0 Then
'案例判断,有多少个函数都加入判断
str=Replace(str,Match.Value,eval(Match.submatches(0)&"("&Match.submatches(1)&")"))
End If
Next
Response.write str

------解决方案--------------------
像这种模板函数重要的是安全判断和参数合法性判断,所以建议针对不同的函数作更详细的参数判断