Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove non-alphanumerical characters excluding space

Tags:

c#

regex

I have this statement:

String cap = Regex.Replace(winCaption, @"[^\w\.@-]", ""); 

that transforms "Hello | World!?" to "HelloWorld".

But I want to preserve space character, for example: "Hello | World!?" to "Hello  World".

How can I do this?

like image 786
CeccoCQ Avatar asked Dec 14 '25 09:12

CeccoCQ


1 Answers

just add a space to your set of characters, [^\w.@- ]

var winCaption = "Hello | World!?";
String cap = Regex.Replace(winCaption, @"[^\w\.@\- ]", "");

Note that you have to escape the 'dash' (-) character since it normally is used to denote a range of characters (for instance, [A-Za-z0-9])

like image 57
James Manning Avatar answered Dec 16 '25 21:12

James Manning



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!