Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Punctuation and Spaces from string using Regex

I am trying to take out all the punctuation and spaces in a string that I am going to encrypt using a Playfair Cipher. I can't figure out why this line doesn't work.

s = Regex.Replace(s, @"[^\w\s]", string.Empty);
like image 513
Gander7 Avatar asked Dec 09 '22 16:12

Gander7


2 Answers

The [^\w\s] means remove anything that's not a word or whitespace character.

Try this instead:

s = Regex.Replace(s, @"[^\w]", string.Empty);

You could also use:

s = Regex.Replace(s, @"\W", string.Empty);

Of course that will leave underscores as those are considered word characters. To remove those as well, try this:

s = Regex.Replace(s, @"[\W_]", string.Empty);

Or this:

s = Regex.Replace(s, @"\W|_", string.Empty);
like image 175
p.s.w.g Avatar answered Dec 11 '22 06:12

p.s.w.g


How about using Linq instead of Regex?

string str = "abc; .d";
var newstr = String.Join("", str.Where(char.IsLetterOrDigit));
like image 39
I4V Avatar answered Dec 11 '22 05:12

I4V