zoukankan      html  css  js  c++  java
  • 正则表达式-简单实例

    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);
            
     
  • 相关阅读:
    Netty与Spring Boot的整合
    Activiti 5.22.0 之自由驳回任务实现(亲测)
    学习机器学习前你应该要知道的一些事
    机器学习中调参的基本思想
    机器学习和深度学习区别的简要概述
    SKlearn中分类决策树的重要参数详解
    世界第二大软件国家如何看待人工智能、机器学习和大数据
    sklearn中的数据预处理和特征工程
    人工智能革命:人类永生还是灭亡(下)
    人工智能革命:人类永生还是灭亡(中)
  • 原文地址:https://www.cnblogs.com/em2464/p/9125675.html
Copyright © 2011-2022 走看看