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

本文关键字:字符串 修改 何使用 Regex Replace | 更新日期: 2023-09-27 18:27:12

假设我想转换这些字符串:

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

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

使用Regex。替换

我想出了这个:

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

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

有什么想法吗?

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

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

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