• [label][翻译][JavaScript Regular Expression]JavaScript Regular Expressions


    原文:http://www.javascriptkit.com/javatutors/re.shtml

    校验用户的输入是每一个软件开发者的必须要做的事情。

    正则表达式与模式

    如何在JavaScript中使用正则表达式呢?这里有两种方式:

    1)字面量语法。

    2)当你需要动态构建正则表达式时,可以通过RegExp()构造函数。

    字面量语法如下:

    var RegularExpression = /pattern/;

    RegExp()构造函数方法如下:

    var RegularExpression = new RegExp("pattern");

    RegExp()方法允许你通过一个字符串来动态构造一个搜索模式,这是一个非常有用的方法,特别是在实现无法知道模式是什么的情况下。

    [原句:The RegExp() method allows you to dynamically construct the search pattern as a string, and is useful when the pattern is not known ahead of time.]

    使用正则表达式来校验一个字符串,那么你必须要定义一个模式字符串来作为搜索的条件,然后使用一个相关字符串方法来表示动作(ie: search, replace etc)。

    模式是通过使用字符串原义字符(string literal characters)和元字符(metacharacters)来定义。

    举个例子,下面的正则表达式是判断一个包含有效的5位美国邮政编码字符串。

    <script type="text/javasript">
    
    function checkpostal(){
    
      var re5digit = /^d{5}$/; //regular expression defining a 5 digit number
      //注意原文该处的实例代码有错误,原文是赋值,正确的如下
      if(document.myform.myinput.value.search(re5digit) === -1){ // if match failed 
    
        alert("Please enter a valid 5 digit number inside form.");
    
      }
    
    }
    
    </script>
    
    <form name="myform">
    
    <input type="text" name="myinput" size="15" />
    
    <input type="button" onClick="checkpostal()" value="check" />
    
    </form>

    解析一下上面所使用的正则表达式,它是用来检查一个包含5位有效数字的字符串,并且只能是一个5位数字。

    var reg5digit = /^d{5}$/;

    • ^表示字符串的开头,使用^元字符要求匹配是从开头开始匹配的
    • d表示一个数字字符,跟在后面的{5}意思是必须5位连续的数字字符
    • $表示的是字符串的结尾,使用$元字符要求匹配在这个字符串后结束

    Translated to English, this pattern states: "Starting at the beginning of the string there must be nothing other than 5 digits. There must also be nothing following those 5 digits."

    用英文来翻译,这个模式声明:“该字符串的开头除了5位数字之外,不能是其他的字符,同时该5位数子后面不能有任何的字符”。

    http://www.javascriptkit.com/javatutors/re2.shtml

  • 相关阅读:
    获取DIV与浏览器顶部相聚一定位置之后移动DIV
    CSS定位小技巧
    jquery动态样式操作
    Python学习笔记1
    KNN算法的感受 2
    KNN算法的感受 1
    Matplotlib安装感想
    安装numpy只需一步简单的方法
    Ubuntu学习笔记3-图书知识点总结
    Hadoop源码如何查看
  • 原文地址:https://www.cnblogs.com/shuman/p/3956730.html
Copyright © 2020-2023  润新知