C# 使用c在字符串中查找单词并替换其后的单词#
嗨,我有一根绳子,这样:C# 使用c在字符串中查找单词并替换其后的单词#,c#,regex,C#,Regex,嗨,我有一根绳子,这样: string values = .....href="http://mynewsite.humbler.com.........href="http://mynewsite.anticipate.com..... and so on 我需要找到“mynewsite:关键字”,然后将“com”替换为“net”。 字符串中有很多“com”,所以我不能简单地使用values.Replace方法。 此外,除了“mysite”之外还有许多其他网站,因此我无法基于http进行搜索
string values = .....href="http://mynewsite.humbler.com.........href="http://mynewsite.anticipate.com..... and so on
我需要找到“mynewsite:关键字”,然后将“com”替换为“net”。
字符串中有很多“com”,所以我不能简单地使用values.Replace方法。
此外,除了“mysite”之外还有许多其他网站,因此我无法基于http进行搜索…(?由于C#regex支持lookbehinds中的量词,您可以尝试下面的regex。然后将匹配的.com
替换为.net
(?<=http:\/\/mynewsite\.)(\w+\.)com
@"(?<=(https?://)?(www\.)?(\S+?\.)?mynewsite(\.\S+?)?)\.com"
我们可以看一下您的实际代码吗?在您的字符串中是否有类似于mynewsite.humbler.com
的字符串,并且是否也要将它们附加到net
中呢?不,我只想用net替换com,您的代码对我来说运行良好。谢谢您的代码不适用于mynewsite.humbler with dash.com
@M42已经询问过了关于同一问题,请向OP提交意见
string str = @"....href=""http://mynewsite.humbler.com"" href=""www.foo.mynewsite.humbler.com"" foo bar href=""http://mynewsite.anticipate.com"" ";
string result = Regex.Replace(str, @"(?<=(https?://)?(www\.)?(\S+?\.)?mynewsite(\.\S+?)?)\.com", ".net");
Console.WriteLine(result);
Console.ReadLine();
....href="http://mynewsite.humbler.net" href="www.foo.mynewsite.humbler.net" foo bar href="http://mynewsite.anticipate.net"