62,244
社区成员




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
List<Tag> list = new List<Tag>()
{
new Tag { Caption="测试1",Url="http://www.test1.com"},
new Tag { Caption="测试2",Url="http://www.test1.com"},
new Tag { Caption="测试3",Url="http://www.test1.com"}
};
string html = "afsafsaf<img title='A测试1BB'/>safasfa";
list.GroupBy(x => x.Url).Select(x => x.First()).Take(5).ToList().ForEach(x =>
{
var regex = new System.Text.RegularExpressions.Regex("(?<=[^>])" + x.Caption + "(?=[^<])");
html = regex.Replace(html, $"<a href='{x.Url}' style='color:#0380d7;' target='_blank'>{x.Caption}</a>", 1);
});
Console.WriteLine(html);
}
}
class Tag
{
public string Caption { get; set; }
public string Url { get; set; }
}
}
代码如上,输出的结果是string html = "afsafsaf<img title='A测试1BB'/>safasfa测试";
Regex regex = new Regex("(?<=^|>)[^<>]*(?=<|$)");
Console.WriteLine(regex.Replace(html,"###$0###"));
没看懂为啥你直接将你的Caption作为正则的一部分传递,正常不应该是获取到值,然后再对这个值进行普通替换么?
也就是
regex.Replace(html,m=>{
return m.Value.Replace("测试1","http://www.baidu,com");
})