2009-09-14 89 views
0

这是我的后续another question。我发现的解决方案非常适合我投掷的每一个测试案例,直到第一次出现的案例出现在我身上。我的目标是使用正则表达式对格式不正确的标签属性进行重新格式化(我知道,可能不是我发现的傻瓜式方法,但忍受着我)。HTML标记替换正则表达式不能正常工作

我的功能:

Public Function ConvertMarkupAttributeQuoteType(ByVal html As String) As String 
    Dim findTags As String = "</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>" 
    Return Regex.Replace(html, findTags, AddressOf EvaluateTag) 
End Function 

Private Function EvaluateTag(ByVal match As Match) As String 
    Dim attributes As String = "\s*=\s*(?:(['""])(?<g1>(?:(?!\1).)*)\1|(?<g1>\S+))" 
    Return Regex.Replace(match.Value, attributes, "='$2'") 
End Function 

EvaluateTag功能正则表达式将正确转换HTML类似

<table border=2 cellpadding='2' cellspacing="1"> 

<table border='2' cellpadding='2' cellspacing='1'> 

你会发现我强迫属性值被单引号包围 - 不用担心这一点。如果最近的属性值在它周围没有任何东西,则它打破的情况。

<table width=100 border=0> 

出来的正则表达式的替换为

<table width='100' border='0>' 

与去年单引号错误外的标签。在我之前我已经承认过我并不擅长正则表达式;我只是没有花时间去理解它能做的一切。所以,我要求帮助调整EvaluateTag正则表达式,以便它可以处理这个最后的情况。

谢谢!

+0

我认为使用HTML清理工具(如您在其他问题上提出的da8)或使用宽容DOM解析HTML并重新导出它会更好。 – TrueWill 2009-09-14 17:26:01

+0

[可以提供一些为什么很难用正则表达式分析XML和HTML的例子吗?](http:// stackoverflow。com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege) – 2011-07-09 20:54:05

+0

[RegEx match open标签除XHTML自包含标签](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – 2011-09-15 14:15:52

回答

1

richardtallent的解释。在玩了一段时间之后,下面的EvaluateTag函数替换似乎正在工作。

任何人都可以看到任何问题吗?我所做的更改是在管道之后的最后一个组中。也许它可以进一步更简化?

Private Function EvaluateTag(ByVal match As Match) As String 
    Dim attributes As String = "\s*=\s*(?:(['""])(?<g1>(?:(?!\1).)*)\1|(?<g1>[^>\s]+))" 
    Return Regex.Replace(match.Value, attributes, "='$2'") 
End Function 

如果没有人回复我可能会接受这个答案。再次感谢!

1

第一个正则表达式函数会通过EvaluateTag 整个匹配,这是整个HTML标记。

但EvaluateTag不忽略最终大于字符...

恐怕我还没有足够的咖啡因还没有通过,整个表达式的工作,但这种调整可能工作(增加了一个大于在人物列表):为什么正则表达式是不工作我指出了正确的方向

Private Function EvaluateTag(ByVal match As Match) As String 
    Dim attributes As String = "\s*=\s*(?:(['"">])(?<g1>(?:(?!\1).)*)\1|(?<g1>\S+))" 
    Return Regex.Replace(match.Value, attributes, "='$2'") 
End Function 
+0

这并没有很好的工作。实际上,它对原始正则表达式没有任何影响。 – 2009-09-15 01:23:32