我需要在C#中使用一个正常的Regex代码来检测字符串中的纯文本URL(http/https/ftp/ftps),并通过在其周围放置一个带有相同url的锚标记来使它们可单击.我已经制作了一个Regex模式,代码附在下面.
但是,如果输入字符串中已存在任何可点击的URL,则上面的代码会在其上添加另一个锚标记.例如,下面代码中的现有子字符串:string sContent:"ftp://www.abc.com'> ftp://www.abc.com "在运行下面的代码时,它上面有另一个锚标记.有没有办法解决它?
string sContent = "ttt <a href='ftp://www.abc.com'>ftp://www.abc.com</a> abc ftp://www.abc.com abbbbb http://www.abc2.com";
Regex regx = new Regex("(http|https|ftp|ftps)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
MatchCollection mactches = regx.Matches(sContent);
foreach (Match match in mactches)
{
sContent = sContent.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
}
Run Code Online (Sandbox Code Playgroud)
此外,我想要一个正则表达式代码,使用"mailto"标签可以点击电子邮件.我可以自己做,但上面提到的双锚标签问题也会出现在其中.
试试这个
Regex regx = new Regex("(?<!(?:href='|>))(http|https|ftp|ftps)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
Run Code Online (Sandbox Code Playgroud)
它应该适用于你的例子.
(?<!(?:href='|>))
是负面的后观,这意味着只有在"href ='"或">"之前不存在模式匹配.
请参阅regular-expressions.info上的外观
在Regexr上看到类似的东西.我不得不从后面的外观中删除交替,但.net应该能够处理它.
更新
为了确保还有(可能)像" <p>ftp://www.def.com</p>
"正确处理的情况,我改进了正则表达式
Regex regx = new Regex("(?<!(?:href='|<a[^>]*>))(http|https|ftp|ftps)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
Run Code Online (Sandbox Code Playgroud)
lookbehind (?<!(?:href='|<a[^>]*>))
现在检查没有"href ='",也没有标签以"
teststring的输出
ttt <a href='ftp://www.abc.com'>ftp://www.abc.com</a> abc <p>ftp://www.def.com</p> abbbbb http://www.ghi.com
Run Code Online (Sandbox Code Playgroud)
是这个表达式
ttt <a href='ftp://www.abc.com'>ftp://www.abc.com</a> abc <p><a href='ftp://www.def.com'>ftp://www.def.com</a></p> abbbbb <a href='http://www.ghi.com'>http://www.ghi.com</a>
Run Code Online (Sandbox Code Playgroud)
小智 5
我在你的示例测试字符串中注意到,如果重复的链接例如ftp://www.abc.com
在字符串中并且已经链接,则结果将是双重锚定该链接.您已经拥有的正则表达式以及@stema提供的正则表达式将起作用,但您需要以不同的方式处理如何替换sContent
变量中的匹配项.
以下代码示例应该为您提供所需内容:
string sContent = "ttt <a href='ftp://www.abc.com'>ftp://www.abc.com</a> abc ftp://www.abc.com abbbbb http://www.abc2.com";
Regex regx = new Regex("(?<!(?:href='|<a[^>]*>))(http|https|ftp|ftps)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
MatchCollection matches = regx.Matches(sContent);
for (int i = matches.Count - 1; i >= 0 ; i--)
{
string newURL = "<a href='" + matches[i].Value + "'>" + matches[i].Value + "</a>";
sContent = sContent.Remove(matches[i].Index, matches[i].Length).Insert(matches[i].Index, newURL);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2409 次 |
最近记录: |