zoukankan      html  css  js  c++  java
  • 通过正则表达式来判断字符串是否为数字组成的

          用正则表达式来验证字符串是否为数字字符串。我们要用到Regex类的isMatch()方法。该类在System.Text.RegularExpressions; 您可以通过using System.Text.RegularExpressions;导入命名空间来访问Regex类。也可以直接通过System.Text.RegularExpressions.Regex 来访问。

    protected bool isNumberic(string message,out int result)
    {
            System.Text.RegularExpressions.Regex rex=
            new System.Text.RegularExpressions.Regex(@"^\d+$");
            result = -1;
            if (rex.IsMatch(message))
            {
                result = int.Parse(message);
                return true;
            }
            else
                return false;
    }

    通过正则表达式判断是否匹配,不仅可以用来做简单的判断匹配,还可以进行精确的匹配,如判断是否是六位的数字字符串,Email匹配等。正则表达式是一种很好的方法。

    protected void Button1_Click(object sender, EventArgs e)
    {
            string message = TextBox1.Text.Trim();
            isNumeric(message); //判断字符串是否为5为整数字符串
    }
    protected void isNumeric(string message)
    {
           if (message != "" && Regex.IsMatch(message, @"^\d{5}$"))
           {
              //成功
              Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('匹配通过!确实是五位的整数字符串')</script>");
           }
           else
               //失败
               Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('匹配失败!')</script>");
    }

    补充
    //正则匹配
    匹配中文字符的正则表达式: [\u4e00-\u9fa5]
    匹配双字节字符(包括汉字在内):[^\x00-\xff]
    匹配空行的正则表达式:\n[\s| ]*\r
    匹配HTML标记的正则表达式:/<(.*)>.*<\/\1>|<(.*) \/>/
    匹配首尾空格的正则表达式:(^\s*)|(\s*$)(像vbscript那样的trim函数)
    匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
    匹配网址URL的正则表达式:http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
    以下是例子:
    利用正则表达式限制网页表单里的文本框输入内容:
    用正则表达式限制只能输入中文:onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')"
    onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))"

    1.用正则表达式限制只能输入全角字符: onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')"
    onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\uFF00-\uFFFF]/g,''))"

    2.用正则表达式限制只能输入数字:onkeyup="value=value.replace(/[^\d]/g,'')
    "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))"

    3.用正则表达式限制只能输入数字和英文:onkeyup="value=value.replace(/[\W]/g,'')
    "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))"

     

  • 相关阅读:
    iOS提醒用户进入设置界面进行重新授权通知定位等功能
    JQ获得ul li 值导成字符串
    “真的”
    原来还有插入代码功能 我还挨个缩进呢 好白菜啊
    ffmpeg 批处理
    DW english
    CI 分页“第一页”问题
    Discuz论坛发帖统计
    我的产品被评为一个“玩具”
    根据css文件采集图片
  • 原文地址:https://www.cnblogs.com/hpuCode/p/2433501.html
Copyright © 2011-2022 走看看