gpt4 book ai didi

c# - 使用 Regex 替换特定的字符串出现但忽略其他基于相邻字符的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:41 25 4
gpt4 key购买 nike

我有一个字符串

   "sub section 15(1) of main section, this might be a <link href="15(1)">15(1)</link>". 

我想使用 Regex.Replace 方法将“15(1)”替换为新的字符串值“15”,但仅限于它单独出现的位置。

我正在使用以下模式,但它不起作用。

 temp = "sub section 15(1) of main section, this might be a <link href="15(1)">15(1)</link>";    
temp = Regex.Replace(temp, @"15(1)", @"15");

输出字符串应该是:

"sub section 15 of main section, this might be a <link href="15(1)">15(1)</link>"

我们将不胜感激。

谢谢

最佳答案

在您的帖子中,您说过要在“单独使用”时替换“15(1)”。这是否意味着它被空格包围?

此方法符合您想要的输出:

string pattern = @"(?<=^|\s)15\(1\)(?=\s|$)";
string result = Regex.Replace(input, pattern, "15");
Console.WriteLine(result);

只有当值出现在行的开头或前面有一个空白字符,并且后面跟着一个空白字符或行尾时,此模式才会匹配。

关于c# - 使用 Regex 替换特定的字符串出现但忽略其他基于相邻字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7531977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com