Marc
Marc

Reputation: 2859

regular expression to reject non-alphanumeric characters

why this regex not work? i want to replace my string by all not default charaacters

legal are = a-Za-z0-9- rest should be replaced and return without the forbidden chars

  protected string FormatToInvalidChars(string InputString)
    {
        string RegexPattern = @"(^[A-Za-z0-9]*)$";

            string s = Regex.Replace(InputString.Trim(), RegexPattern, "$1");

            return s;

    }

Upvotes: 0

Views: 723

Answers (3)

Konamiman
Konamiman

Reputation: 50273

Try the following:

Regex.Replace(InputString.Trim(), @"[^A-Za-z0-9-]", "");

(assuming that the hyphen is also legal, as you say in the question)

Upvotes: 1

Joey
Joey

Reputation: 354506

Your pattern makes no sense. You're matching only a single-character string that way.

What you want is probably to replace

[^A-Za-z0-9]

by an empty string.

Upvotes: 1

YOU
YOU

Reputation: 123831

string s = Regex.Replace(InputString.Trim(),@"[^A-Za-z0-9]+","");

Upvotes: 1

Related Questions