I'm trying to replace all "non alphanumeric characters" and "multiple spaces" with just 1 single space
I have 2 working solutions, however i'm wondering if its possible to combine them efficiently?
Given
var str = "ASD S-DF 2134 4@# 4 234234 #$)(u SD";
var options = RegexOptions.None;
Solution for non alphanumeric characters
var rgxAlpha = new Regex("[^a-zA-Z0-9]");
str = rgxAlpha.Replace(str, " ", options);
Solution for multiple spaces
var regexSpace = new Regex(@"[ ]{2,}", options);
str = regexSpace.Replace(str, " ");
Expected Result
ASD S DF 2134 4 4 234234 u SD
Just the below would be enough, since [^a-zA-Z0-9]+
matches also the spaces, you don't need to add [ ]{2,}
explicitly.
string result = Regex.Replace(str, @"[^a-zA-Z0-9]+", " ");
DEMO
Assuming they both work:
var rgxPattern = new Regex(@"[^a-zA-Z0-9]+|[ ]{2,}");
Just add a | between them.
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