Skip to main content
 首页 » 编程设计

c#之替换一个子字符串的值,但一个

2024年02月05日25xxx_UU

我需要用另一个字符串替换所有出现的子字符串。但我不想替换主字符串中特定子字符串中出现的子字符串。

示例

string main = "The value for v and p are not v and p" 
string replacestring= "v"; 
main = main.Replace(replacestring,12); 

结果

main = The 12alue for 12 and p are not 12 and p 

预期结果

main =The value for 12 and p are not v and p. 

所以基本上我不是要跳过第一次出现的子字符串,而是要跳过整个子字符串 value。我不希望它被 replacestring 的任何值替换。我试图找到子字符串 value 第一次出现的索引并跳过接下来的 4 个字符然后替换。但它对我来说效率不够,因为可以多次出现 value。

请您参考如下方法:

如果要将第一个 v 替换为整个单词,请使用

var rx1 = new Regex(@"\bv\b"); 
var t = rx1.Replace("The value for v and p are not v and p", "12", 1); 

参见 Regex.Replace方法。最后一个 1 参数是 count(替换可以发生的最大次数。)

正则表达式 \bv\b 匹配任何用非单词字符(非字母、非数字和非 _ s).

无论何时动态构建正则表达式,请确保

  • 使用逐字字符串文字,以便仅使用单个反斜杠来转义正则表达式元字符
  • Regex.Escape 方法应该在您需要匹配某些值时使用literally。

因此,使用

var s = "v"; 
var rx1 = new Regex(@"\b" + Regex.Escape(s) + @"\b"); 
// or 
// var rx1 = new Regex(string.Format(@"\b{0}\b", Regex.Escape(s))); 
var t = rx1.Replace("The value for v and p are not v and p", "12", 1);