keep alphanum + additional char

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
olibara
Forum Newbie
Posts: 2
Joined: Mon Jul 19, 2010 6:04 am

keep alphanum + additional char

Post 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
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: keep alphanum + additional char

Post 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
}
olibara
Forum Newbie
Posts: 2
Joined: Mon Jul 19, 2010 6:04 am

Re: keep alphanum + additional char

Post by olibara »

Thanks a lot ridgerunner !
Post Reply