2015-04-05 78 views
-2

我的函数需要替换字符串中的标签,如果其中提取的数据有url。 例如:vb.net正则表达式 - 替换标签而不替换span标签

www.cnn.com 

这工作正常,但是当我有这样一个字符串:

<a href=www.cnn.com><span style="color: rgb(255, 0, 0);">www.cnn.com</span></a> 

我只得到:

www.cnn.com 

<a href=www.cnn.com>www.cnn.com</a> 

将被取代

当我真的想要sta y与:

<span style="color: rgb(255, 0, 0);">www.cnn.com</span> 

我需要添加到它的代码工作?

这是我的函数:

Dim ret As String = text 

'If it looks like a URL 
Dim regURL As New Regex("(www|\.org\b|\.com\b|http)") 
'Gets a Tags regex 
Dim rxgATags = New Regex("<[^>]*>", RegexOptions.IgnoreCase) 

'Gets all matches of <a></a> and adds them to a list 
Dim matches As MatchCollection = Regex.Matches(ret, "<a\b[^>]*>(.*?)</a>") 

'for each <a></a> in the text check it's content, if it looks like URL then delete the <a></a> 
For Each m In matches 
'tmpText holds the data extracted within the a tags. /visit at.../www.applyhere.com 
     Dim tmpText = rxgATags.Replace(m.ToString, "") 

     If regURL.IsMatch(tmpText) Then 
      ret = ret.Replace(m.ToString, tmpText) 
     End If 
Next 

Return ret 
+2

使用此“@”] *>“'正则表达式。 – 2015-04-05 11:17:20

回答

0

我加入这个我的代码:

'Selects only the A tags without the data extracted between them 
Dim rxgATagsOnly = New Regex("</?a\b[^>]*>", RegexOptions.IgnoreCase) 

    For Each m In matches 
     'tmpText holds the data extracted within the a tags. /visit at.../www.applyhere.com 
     Dim tmpText = rxgATagsContent.Replace(m.ToString, "") 

     'if the data extract between the tags looks like a URL then take off the a tags without touching the span tags. 
     If regURL.IsMatch(tmpText) Then 
      'select everything but a tags 
      Dim noATagsStr As String = rxgATagsOnly.Replace(m.ToString, Environment.NewLine) 
      'replaces string with a tag to non a tag string keeping it's span tags 
      ret = ret.Replace(m.ToString, noATagsStr) 

     End If 
    Next 

所以从字符串:

<a href=www.cnn.com><span style="color: rgb(255, 0, 0);">www.cnn.com</span></a> 

我只选择了与阿维纳什·拉吉正则表达式 和一个标签然后用“”替换它们。 谢谢大家回答。

0

下面的正则表达式将删除所有的HTML标签:

string someString = "<a href=www.one.co.il><span style=\"color: rgb(255, 0, 255);\">www.visitus.com</span></a>"; 

string target = System.Text.RegularExpressions.Regex.Replace(someString, @"<[^>]*>", "", RegexOptions.Compiled).ToString(); 

这是正则表达式,你想:我的代码<[^>]*>

结果:www.visitus.com

0

您可以使用以下正则表达式 - <a\s*[^<>]*>|</a> - 这将匹配所有<a>节点,包括开始和结束节点。

你不需要使用regURL,这可以构建到rxATags正则表达式中。我们可以通过检查hrefregURL alternatives, then grab everything in between the opening and close`标签来确保它是一个URL参考<a>标签,然后仅使用它们之间的内容。

Dim ret As String = "<a href=www.one.co.il><span style=""color: rgb(255, 0, 255);"">www.visitus.com</span></a>" 
'Gets a Tags regex 
Dim rxgATags = New Regex("(<a\s*[^<>]*href=[""']?(?:www|\.org\b|\.com\b|http)[^<>]*>)((?>\s*<(?<t>[\w.-]+)[^<>]*?>[^<>]*?</\k<t>>\s*)+)(</a>)", RegexOptions.IgnoreCase) 
Dim replacement As String = "$2" 
ret = rxgATags.Replace(ret, replacement) 

enter image description here