0
str = "R57 & R1 & R11"

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

I want to replace only R1 => true

generated Output = "R57 & true & true1"

Correct Output = "R57 & true & R11"

2
  • Try string.Replace("R1 ","true ") Commented Apr 5, 2021 at 14:22
  • 2
    string result = Regex.Replace(str, @"\bR1\b", "true"); Commented Apr 5, 2021 at 14:22

2 Answers 2

4

What about this,

var str = "R57 & R1 & R11";
var result = str.Replace(" R1 "," true ") //Look at spaces before and after "R1"

or

using System.Text.RegularExpressions;
...
string result = Regex.Replace(str, @"\bR1\b", "true");  //`\b` denotes boundary

.NetFiddle

Sign up to request clarification or add additional context in comments.

2 Comments

regex is worked for me because sometime space is not included . Thanks
Elegant approach is to use RegEx, str.Replace() is just a hack. I am glad you choose RegEx over str.Replace() Use of \b is explained by @DmitryBychenko. \b denotes match must be present in between boundary
2

You can try regular expressions:

using System.Text.RegularExpressions;

...

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

we want whole words only to be replaced into "true".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.