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);
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);
How about using Linq instead of Regex?
string str = "abc; .d";
var newstr = String.Join("", str.Where(char.IsLetterOrDigit));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With