JS-RegExp

正则表达式定义与其属性

    var pattern1 = /\[bc\]at/i;
    console.log(pattern1.global);     //false
    console.log(pattern1.ignoreCase); //true
    console.log(pattern1.multiline);  //false
    console.log(pattern1.lastIndex);  //0
    console.log(pattern1.source);     //"\[bc\]at"

    var pattern2 = new RegExp("\\[bc\\]at", "i");
    console.log(pattern2.global);     //false
    console.log(pattern2.ignoreCase); //true
    console.log(pattern2.multiline);  //false
    console.log(pattern2.lastIndex);  //0
    console.log(pattern2.source);     //"\[bc\]at"

toString()

    var pattern = new RegExp("\\[bc\\]at", "gi");
    console.log(pattern.toString());    // /\[bc\]at/gi
    console.log(pattern.toLocaleString());    // /\[bc\]at/gi

浏览器支持的正则属性

    var text = "this has been a short summer";
    var pattern = /(.)hort/g;
    /**
     * Note:
     *   Opera doesn't support input, lastMatch, lastParen, or multiline.
     *   Internet Explorer And Chrome doesn't support multiline.
     */
    if (pattern.test(text)){
        console.log(RegExp.input);   //this has been a short summer ==> RegExp.$_
        console.log(RegExp.leftContext);  //this has been a ==> RegExp["$`"]
        console.log(RegExp.rightContext); // summer ==> RegExp["$'"]
        console.log(RegExp.lastMatch);    //short ==> RegExp["$&"]
        console.log(RegExp.lastParen);    //s ==> RegExp["$+"]
//支持则false 不支持否则undefined ==>RegExp["$*"]
        console.log(RegExp.multiline);    

    }

提取匹配的组,下标从 1 开始

    var text = "this has been a short summer";
    var pattern = /(..)or(.)/g;
    // 匹配组的提取
    if (pattern.test(text)){
        console.log(RegExp.$1);       //sh
        console.log(RegExp.$2);       //t
    }

exec() 方法的使用

    var text = "mom and dad and baby";
    var pattern = /mom( and dad( and baby)?)?/gi;
    var matches = pattern.exec(text);
    console.log(matches.index);    //0
    console.log(matches.input);    //"mom and dad and baby"
    console.log(matches[0]);       //"mom and dad and baby"
    console.log(matches[1]);       //" and dad and baby"
    console.log(matches[2]);       //" and baby"