Parsing a string, removing any NON alphanumeric characters usingregex

D

DotNetNewbie

Hi,

I want to parse a string, ONLY allowing alphanumeric characters and
also the underscore '_' and dash '-' characters.

Anything else in the string should be removed.

I think my regex is looking like:

^([\w\d_-])*$


Now if I have this code:

string username = "mrcsharpis_so_cool!!!";

How can I strip all the characters that I dont' want?
 
A

Arne Vajhøj

DotNetNewbie said:
I want to parse a string, ONLY allowing alphanumeric characters and
also the underscore '_' and dash '-' characters.

Anything else in the string should be removed.

I think my regex is looking like:

^([\w\d_-])*$

^[\w-]*$

should do - \w includes digits and underscore.
Now if I have this code:

string username = "mrcsharpis_so_cool!!!";

How can I strip all the characters that I dont' want?

Try:

Regex.Replace(username, @"[^\w-]+", "")

Arne
 
D

DotNetNewbie

DotNetNewbie said:
I want to parse a string, ONLY allowing alphanumeric characters and
also the underscore '_' and dash '-' characters.
Anything else in the string should be removed.
I think my regex is looking like:
^([\w\d_-])*$

^[\w-]*$

should do - \w includes digits and underscore.
Now if I have this code:
string username = "mrcsharpis_so_cool!!!";
How can I strip all the characters that I dont' want?

Try:

Regex.Replace(username, @"[^\w-]+", "")

Arne

Replace doesn't take only 2 arguements, that doesn't work?
 
A

Arne Vajhøj

DotNetNewbie said:
DotNetNewbie said:
I want to parse a string, ONLY allowing alphanumeric characters and
also the underscore '_' and dash '-' characters.
Anything else in the string should be removed.
I think my regex is looking like:
^([\w\d_-])*$

^[\w-]*$

should do - \w includes digits and underscore.
Now if I have this code:
string username = "mrcsharpis_so_cool!!!";
How can I strip all the characters that I dont' want?
Try:

Regex.Replace(username, @"[^\w-]+", "")

Replace doesn't take only 2 arguements, that doesn't work?

There are 3 arguments in the call I suggest.

And Regex.Replace does have such a method:

http://msdn2.microsoft.com/en-us/library/e7f5w83z.aspx

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top