当前位置: 动力学知识库 > 问答 > 编程问答 >

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: