如何使用Regex.Replace修改匹配的字符串?

时间:2013-08-10 11:58:49

标签: c# regex

我想要转换这些字符串:

www.myexample.com和http://www.myexample.com
进入:

<a href='http://www.myexample.com'>http://www.myexample.com</a>

使用Regex.Replace

我想出了这个:

Regex.Replace(string, pattern, "<a href=\"$&\">$&</a>")

我的问题是我不知道如何检查匹配的字符串$&amp;以http://开头,并在必要时添加。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果你不必考虑https或类似的东西,你可以使用它:

Regex.Replace(string, @"(?:http://)?(.+)", "<a href=\"http://$1\">http://$1</a>")