Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace non alphanumeric characters and multiple spaces with just 1 space

Tags:

c#

regex

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
like image 766
TheGeneral Avatar asked Sep 19 '25 17:09

TheGeneral


2 Answers

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

like image 83
Avinash Raj Avatar answered Sep 22 '25 08:09

Avinash Raj


Assuming they both work:

var rgxPattern = new Regex(@"[^a-zA-Z0-9]+|[ ]{2,}");

Just add a | between them.

like image 21
Saverio Terracciano Avatar answered Sep 22 '25 08:09

Saverio Terracciano