zoukankan      html  css  js  c++  java
  • javascript 正则表达式

    //两种创建方式
    
    var box = new RegExp('box');        //第一个参数字符串
    var box = new RegExp('box', 'ig'); //第二个参数可选模式修饰符

    var box=/box/; //直接用两个反斜杠
    var box=/box/ig; //在第二个斜杠后面加上模式修饰符
    
    /*2.测试正则表达式
    RegExp对象包含两个方法:test()和exec(),功能基本相似,用于测试字符串匹配。*/

    /*使用new运算符的test方法示例*/
    var pattern = new RegExp('box','i'); //创建正则模式,不区分大小写
    var str = 'This isaBox!'; //创建要比对的字符串
    alert(pattern.test(str)); //通过test()方法验证是否匹配
    /*使用字面量方式的test方法示例*/
    var pattern = /box/i; //创建正则模式,不区分大小写
    var str = 'This isaBox!';
    alert(pattern.test(str));
    /*使用一条语句实现正则匹配*/
    alert(/box/i.test('ThisisaBox!')); //模式和字符串替换掉了两个变量
    /*使用exec返回匹配数组*/
    var pattern = /box/i;
    var str='This isaBox!';
    alert(pattern.exec(str)); //匹配了返回数组,否则返回null
    //PS:exec方法还有其他具体应用,我们在获取控制学完后再看。
    
    
    /*3.使用字符串的正则表达式方法
    除了test()和exec()方法,String对象也提供了4个使用正则表达式的方法。*/

    /*使用match方法获取获取匹配数组*/
    var pattern=/box/ig; //全局搜索
    var str='This isaBox!,ThatisaBoxtoo';
    alert(str.match(pattern)); //匹配到两个Box,Box
    alert(str.match(pattern).length); //获取数组的长度
    /*使用search来查找匹配数据*/
    var pattern=/box/ig;
    var str='This isaBox!,ThatisaBoxtoo';
    alert(str.search(pattern)); //查找到返回位置,否则返回-1
    PS:因为search方法查找到即返回,也就是说无需g全局
    /*使用replace替换匹配到的数据*/
    var pattern=/box/ig;
    var str='This isaBox!,ThatisaBoxtoo';
    alert(str.replace(pattern,'Tom')); //将Box替换成了Tom
    /*使用split拆分成字符串数组*/
    var pattern=//ig;
    var str='This isaBox!,ThatisaBoxtoo';
    alert(str.split(pattern)); //将空格拆开分组成数组

    /*使用静态属性*/
    var pattern=/(g)oogle/;
    var str='This isgoogle!';
    pattern.test(str); //执行一下
    alert(RegExp.input); //Thisisgoogle!
    alert(RegExp.leftContext); //Thisis
    alert(RegExp.rightContext); //
    alert(RegExp.lastMatch); //google
    alert(RegExp.lastParen); //g
    alert(RegExp.multiline); //false
    
    //PS:Opera不支持input、lastMatch、lastParen和multiline属性。IE不支持multiline属性。
  • 相关阅读:
    转载 :sql server 2005 无法删除数据库 "#Test",因为该数据库当前正在使用
    leetcode 1
    leetcode 2
    leetcode 242
    leetcode171
    leetcode 122
    leetcode 100
    算法:号码转换问题
    2014年10月29日 00:23 长沙
    算法:poj1066 宝藏猎人问题。
  • 原文地址:https://www.cnblogs.com/suihui/p/3505690.html
Copyright © 2011-2022 走看看