Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What C# regex expression can be used to strip out dots (.) in a string?

Tags:

c#

.net

asp.net

I need a string with non alpha-numeric characters etc stripped out of it; I used the following:

wordsstr = Regex.Replace(wordsstr, "[^A-Za-z0-9,-_]", "");

The problem being dots (.)s are left in the string yet they are not specified to be kept. How could I make sure dots are gotten rid of too?

Many thanks.

like image 627
James Avatar asked Feb 04 '26 04:02

James


1 Answers

You are specifying that they need to be kept - you're using ,-_ which is everything from U+002C to U+005F, including U+002E (period).

If you meant the ,-_ to just mean comma, dash and underscore you'll need to escape the dash, such as:

wordsstr = Regex.Replace(input, @"[^A-Za-z0-9,\-_]", "");

Alternatively, (as in Oded's comment) put the dash as the first or last character in the set, to prevent it being interpreted as a range specifier:

wordsstr = Regex.Replace(input, "[^A-Za-z0-9,_-]", "");

If that's not the aim, please be more specific: "non alpha-numeric characters etc" isn't really enough information to go on.

like image 133
Jon Skeet Avatar answered Feb 06 '26 12:02

Jon Skeet



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!