CeccoCQ
CeccoCQ

Reputation: 3754

Remove non-alphanumerical characters excluding space

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?

Upvotes: 3

Views: 1248

Answers (3)

Johnny
Johnny

Reputation: 1575

Try this:

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

Upvotes: 0

Ian P
Ian P

Reputation: 12993

Here you go...

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

Upvotes: 1

James Manning
James Manning

Reputation: 13579

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])

Upvotes: 4

Related Questions