简体   繁体   English

C#正则表达式中的无效字符

[英]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. 如果计数> 0,则表示存在无效字符。 But it never returns according to my expectations. 但是它永远不会按照我的期望返回。 Please tell me what I am doing wrong. 请告诉我我在做什么错。 This is strictly c# 这是严格的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. 您也可以查看\\w字符类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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