C# 将值替换为字符串

C# 将值替换为字符串,c#,string,C#,String,我只想替换R1=>true 生成的输出=R57&true&true1 正确的输出=R57&true&R11这个呢 str = "R57 & R1 & R11" string.Replace("R1","true") 或 您可以尝试使用正则表达式: 我们只希望将整个单词替换为true。尝试string.ReplaceR1,true string result=Regex.Replacestr,@\bR1\b,true;

我只想替换R1=>true

生成的输出=R57&true&true1

正确的输出=R57&true&R11

这个呢

str = "R57 & R1 & R11"

string.Replace("R1","true")

您可以尝试使用正则表达式:


我们只希望将整个单词替换为true。

尝试string.ReplaceR1,true string result=Regex.Replacestr,@\bR1\b,true;regex为我工作。Thanksregex为我工作,因为有时不包括空间。谢天谢地的方法是使用RegEx,str.Replace只是一个hack。我很高兴您选择RegEx而不是str。替换\b的用法由@DmitryBychenko解释\b表示边界之间必须存在匹配
var str = "R57 & R1 & R11";
var result = str.Replace(" R1 "," true ") //Look at spaces before and after "R1"
using System.Text.RegularExpressions;
...
string result = Regex.Replace(str, @"\bR1\b", "true");  //`\b` denotes boundary
using System.Text.RegularExpressions;

...

string result = Regex.Replace(str, @"\bR1\b", "true");