Page 1 of 1

keep alphanum + additional char

Posted: Mon Jul 19, 2010 6:09 am
by olibara
Hello

In C# I'm using this expression to remove all non-aphanum char

Code: Select all

Key=Regex.Replace(value.ToUpper(), "[\\W]", "");
But I also want to keep some extra char as "+-@"

What can be the expression to do that ?

Thank for your help

Re: keep alphanum + additional char

Posted: Tue Jul 20, 2010 12:08 am
by ridgerunner
The [\W] is a character class matching one non-word character.

Instead, you can use a negative character class containing a word char plus the ones you want to preserve like so:
[^\w+\-@]
Which says: "match a character that is not a word char or a + or a - or a @"

Your code might look something like this:

Code: Select all

try {
    Key=Regex.Replace(value.ToUpper(), @"[^\w+\-@]", "");
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

Re: keep alphanum + additional char

Posted: Tue Jul 20, 2010 12:48 am
by olibara
Thanks a lot ridgerunner !