• 正则表达式-简单实例


    http://www.runoob.com/regexp/regexp-tutorial.html

    http://www.runoob.com/js/js-regexp.html

    实例1:模式匹配

      

           var searchString="Now is the time and this is the time and that is the time";
                var pattern=/tw*e/g;
                var matchArray;
                var str="";
                while((matchArray=pattern.exec(searchString))!=null){
                    console.log(searchString);
                    console.log(pattern.lastIndex);
    
                    console.log(matchArray);
                    str+="at"+matchArray.index+" we found "+matchArray[0]+'
    ';
                }
                console.log(str);
                console.log(matchArray);
    
    
    
                    //实例2
                var re=/a(p+).*(pie)/ig;//   a 一到多个p 除换行以外的任意字符 零到多次 pie
                var result=re.exec('The apples in the apple pie are tart');
                console.log(result);

    结果:

    分析:

    一、使用字符串的方法

      search()和replace()   参数可以是字符串也可以是正则表达式

      search()用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串,并返回子串的起始位置。

      replace()用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

    二、使用RegExp对象

      test()用于检测一个字符串是否匹配某个模式,如果字符串中含有匹配的文本,则返回true,否则返回false。

           exec()用于检索字符串中的正则表达式的匹配,该函数返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为null。

      exec()方法执行,如果没有找到一个匹配,返回null,如果找到了一个匹配,返回带有匹配信息的一个对象。

              返回的数组中,所包含的是实际匹配的值、在字符串中找到匹配的索引、任何带括号的子字符串匹配(正则表达式中带括号的字符串),以及最初的字符串。

          实例2中

            var re=/a(p+).*(pie)/ig;//   a 一到多个p 除换行以外的任意字符 零到多次 pie     带括号的子字符串指(p+)和(pie)
                var result=re.exec('The apples in the apple pie are tart');
                console.log(result);
            
     
  • 相关阅读:
    构建之法作业要求 20160922
    构建之法作业截止 20160908
    作业成绩 20160901
    动态范围理解
    解像力理解以及单位换算;
    QT:基本知识(一);
    qml: 截图(单窗口);
    (转载)python: getopt的使用;
    python: with的使用;
    qml: 自定义输入框
  • 原文地址:https://www.cnblogs.com/em2464/p/9125675.html
Copyright © 2020-2023  润新知