开发者

regular expression to reject non-alphanumeric characters

开发者 https://www.devze.com 2022-12-14 05:15 出处:网络
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

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");

            retur开发者_高级运维n s;

    }


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


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.


Try the following:

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消