Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace specific string C#?

Tags:

string

c#

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#?

like image 599
Arry Avatar asked Jan 27 '26 04:01

Arry


2 Answers

You need a regex pattern that only matches "a" on word boundaries. "\b" in a regex pattern denotes a word boundary:

Regex.Replace("this is a car", @"\ba\b", "")

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".

like image 183
mmx Avatar answered Jan 29 '26 19:01

mmx


What do you mean with 'isolated occurence'? Is it perhaps something like this you're really after:

data.Replace(" a ", " ");
like image 27
Christoffer Avatar answered Jan 29 '26 18:01

Christoffer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!