Home > Back-end >  How can I only replace a specific word in a string using C#?
How can I only replace a specific word in a string using C#?

Time:06-03

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

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?

CodePudding user response:

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

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

.Try Online

  •  Tags:  
  • c#
  • Related