简体   繁体   中英

C# Regex for invalid characters

Hi I have a requirement to validate an input that should accept only alphanumeric, -, _ To test this i am using the following code

 string pattern = @"[^a-z A-Z 0-9._-]$";
        var matches = Regex.Matches(m_ModelName.Value, pattern, RegexOptions.IgnoreCase);
        return (matches.Count > 0);

if the count is >0 it means there are invalid characters. But it never returns according to my expectations. Please tell me what I am doing wrong. This is strictly c#

string pattern = @"[^a-z A-Z 0-9._-]$";

This regex just matches the last character in the string (because of the $ anchor).

You probably want something like:

 string pattern = @"^[a-zA-Z0-9._-]+$";
 return Regex.IsMatch(m_ModelName.Value, pattern, RegexOptions.IgnoreCase);

Also you may look at the \\w character class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM