Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I only replace a specific word in a string using C#?

I have a string

 var query =  select id, Details.Id, Details.Info.Id from DetailsItem

I want to replace Details with [Details], so I am using

query.Replace(" Details", " [Details]");

I get the following

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select id, [Details].Id, [Details].Info.Id from [Details]Item

but it replaces DetailsItem which I dont want. How can I only replace if the word is Details only?

>Solution :

You should use Regex.Replace() method with word boundary i.e \b,

string queryResult = Regex.Replace(query, @"\bDetails\b", "[Details]", RegexOptions.None);  

.Try Online

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading