试图获得一个匹配 url 的正则表达式,例如“http://www.test.com”,然后在它周围放置锚标签 - 该部分已经在使用以下内容:
regex = @"(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:;,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:;,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:;,.]*\)|[A-Z0-9+&@#\/%=~_|$])"
msg = r.Replace( msg, "<a target=\"_blank\" href=\"$0\">$0</a>" );
但是当输入文本中有图像标签时,它会错误地将锚标签放在图像标签的 src 属性中,例如
<img src="<a>...</a>" />;
到目前为止,我正在尝试绕过它:(不工作)
regex = @"(?!(src=""))(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:;,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:;,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:;,.]*\)|[A-Z0-9+&@#\/%=~_|$])"
编辑:
(示例测试输入):
<p>
www.test1.com<br />
<br />
http://www.test2.com<br />
<br />
https://www.test3.com<br />
<br />
"https://www.test4.com<br />
<br />
'https://www.test4.com<br />
<br />
="https://www.test4.com</p>
<p>
</p>
<p>
<img alt="" src="..." style="width: 500px; height: 375px;" /></p>
(示例输出):
<p>
<a target="_blank" href="www.test1.com">www.test1.com</a><br />
<br />
<a target="_blank" href="http://www.test2.com">http://www.test2.com</a><br />
<br />
<a target="_blank" href="https://www.test3.com">https://www.test3.com</a><br />
<br />
"<a target="_blank" href="https://www.test4.com">https://www.test4.com</a><br />
<br />
'<a target="_blank" href="https://www.test4.com">https://www.test4.com</a><br />
<br />
="<a target="_blank" href="https://www.test4.com">https://www.test4.com</a></p>
<p>
</p>
<p>
<img alt="" src="<a target="_blank" href="...">...</a>" style="width: 500px; height: 375px;" /></p>
(所需的输出):
<p>
<a target="_blank" href="www.test1.com">www.test1.com</a><br />
<br />
<a target="_blank" href="http://www.test2.com">http://www.test2.com</a><br />
<br />
<a target="_blank" href="https://www.test3.com">https://www.test3.com</a><br />
<br />
"<a target="_blank" href="https://www.test4.com">https://www.test4.com</a><br />
<br />
'<a target="_blank" href="https://www.test4.com">https://www.test4.com</a><br />
<br />
="<a target="_blank" href="https://www.test4.com">https://www.test4.com</a></p>
<p>
</p>
<p>
<img alt="" src="..." style="width: 500px; height: 375px;" /></p>