我在自定义验证器中使用正则表达式来打印字母数字值,但它不起作用 [英] I am using regex in custom validator to print alphanumeric value but it is not working

查看:79
本文介绍了我在自定义验证器中使用正则表达式来打印字母数字值,但它不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
   {

         
         System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("([0-9a-z]{1,10})");
          args.IsValid = r.IsMatch(TextBox2.Text);


   }

推荐答案

上限+下限+数字。



Upper + Lower + Numbers.

(?-x)[0-9A-Za-z]{1,10}





更低+数字。





Lower + Numbers.

(?-x)[0-9a-z]{1,10}







你的表达错了,用这个测试了:






Your expression was wrong, tested it with this:

bool foundMatch = false;
try {
	foundMatch = Regex.IsMatch(subjectString, "([0-9a-z]{1,10})");
    } 
catch (ArgumentException ex)
    {
	// Syntax error in the regular expression
    }







你还应该在你的使用中加上 System.Text.RegularExpressions



我还想补充一点 {1,10} 由于缺少锚点而在原始表达式中没有做任何事情,并且几乎可以匹配任何东西。 />


以下测试(? - x)[0-9A-Za-z] {1,10} 字符串:






You should also put System.Text.RegularExpressions in your Usings.

I also want to add that {1,10} isn't really doing anything in your original expression because of a lack of anchors and will match pretty much anything.

Tested (?-x)[0-9A-Za-z]{1,10} on the following strings:

abc123abc1
123812shdkfjs12g312t3
sdf6s876374kGFHGF26453165243
fsjdtfs7d65fs764123h1f2h3gfAHSGDF123
ASDASFJDSDFJHSksdgsdkfg123123123


每次输入方法时都不应创建正则表达式。最好将表达式变量添加为类的静态成员。



如解决方案1中所述,将RegularExpressions命名空间添加到您的使用中会更方便部分。

You should not create your regular expression every time you enter the method. It is better to add the expression variable as a static member of the class.

As suggested in Solution 1, it is more convenient to add the RegularExpressions namespace to your using section.
using System.Text.RegularExpressions;




private static Regex alphaNumExpression = new Regex("^[0-9a-z]{1,10}


,RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);



请注意开始 ^ 并结束


这篇关于我在自定义验证器中使用正则表达式来打印字母数字值,但它不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆