Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 特殊字符串替换函数_C#_Regex - Fatal编程技术网

C# 特殊字符串替换函数

C# 特殊字符串替换函数,c#,regex,C#,Regex,我必须用我预定义的链接替换特定链接。 string content = @"<html>" +" <a href='http://www.yourdomain.com' style='width:10px;'>Click Here</a>" +" <br>" +" <a href='http://www.yourdomain.com/product

我必须用我预定义的链接替换特定链接。

string content = @"<html>"
                +" <a href='http://www.yourdomain.com' style='width:10px;'>Click Here</a>"
                +" <br>"
                +" <a href='http://www.yourdomain.com/products/list.aspx' style='width:10px;'>Click Here</a>"
                +" </html>";
我也尝试函数。

string pattern = @"\bhttp://www.yourdomain.com\b";
string replace = "http://www.mydomain.com";
string result = Regex.Replace(content, pattern, replace);
但我得到了同样的结果。如下图所示。

<html> 
<a href='http://www.mydomain.com' style='width:10px;'>Click Here</a> 
<br> 
<a href='http://www.mydomain.com/products/list.aspx' style='width:10px;'>Click Here</a> 
</html>
<html> 
<a href='http://www.mydomain.com' style='width:10px;'>Click Here</a> 
<br> 
<a href='http://www.yourdomain.com/products/list.aspx' style='width:10px;'>Click Here</a> 
</html>

在replace调用中的字符串参数末尾添加

result = content.Replace("'http://www.yourdomain.com'", "'http://www.mydomain.com'");

这样,您将只替换没有子链接的URL。

除了通常的警告之外,alphanum(
\w
)和非alphanum(
\w
)之间的单词边界
\b
匹配,因此它在
m
之间以及
m
/code>之间匹配

要明确禁止URL结束后出现
/
,您可以使用负前瞻,请参阅:

http://www.yourdomain.com(?!/)

看看Html Agility Pack-它比正则表达式或字符串函数更适合解析Html。如果它和您的问题一样微不足道,那么
string result=content.Replace(“'http://www.yourdomain.com'", "'http://www.mydomain.com'");
(我刚刚添加了撇号)。如果可能使用
而不是
,可能会添加第二个替换。除非您确定它现在或将来不会使用。这是一个完美的解决方案。非常感谢@Robin。
string content = @"<html>"
                    +" <a href='http://www.yourdomain.com' style='width:10px;'>Click Here</a>"
                    +" <br>"
                    +" <a href='http://www.yourdomain.com/products/list.aspx' style='width:10px;'>Click Here</a>"
                    +" </html>";

string pattern = string.Format("{0}(?!/)", "http://www.yourdomain.com");
string replace = "http://www.mydomain.com";
string result = Regex.Replace(content, pattern, replace);
http://www.yourdomain.com([^/])
result = content.Replace("'http://www.yourdomain.com'", "'http://www.mydomain.com'");