I am trying to replace a specific sub string from a string in C#.
My string is: This is a car.
And I am trying to replace ‘a’ with string.Empty from the string with this code:
data = data.Replace("a", string.Empty);
But my output is :
This is c r.
I just want to remove isolated occurence of ‘a’, and not when this char/word is used in some other word (like car).
I want a output like ths: This is car.
How can I do this in C#?
You need a regex pattern that only matches “a” on word boundaries.
"\b"in a regex pattern denotes a word boundary:If you want to match uppercase “A” as well, make sure your pattern is ignoring case (
RegexOptions.IgnoreCase) or explicitly add “A” to the pattern like"\b[Aa]\b".