Javascript Regular Expressions - Objects and Methods

  1. Create a RegExp object
  2. Regular example
  3. Regular Expression Resources

1. Create a RegExp object

1-1. There are two ways to create regular expressions: new RegExp(expression) and direct literals.

var exp1 = /(^\s+)|(\s+$)/g;  //使用直接字面量创建
var exp2 = new RegExp("(^\\s+)|(\\s+$)","g");  //使用RegExp对象创建

1-2, RegExp object method

compile  //编译正则表达式,把正则表达式编译为内部格式
exec    //检索字符串中指定的值。返回找到的值,并确定其位置
test    //检索字符串是否存在模式,返回 true 或 false
match   //是获取正则匹配到的结果,以数组的形式返回
replace  // 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

1-3. Each regular expression can have one or more flags

g: //全局模式,即模式将被应用于所有字符串,而非在发现第一个匹配项时立即停止;
i ://不区分大小写模式,即在确定匹配项时忽略模式与字符串的大小写;
m://多行模式,即在到达一行文本末尾时还会继续查找下一行中是否存在与模式匹配的项。
如果多个标志同时使用时,则写成:gmi 。

1-4. Metacharacters in regular expressions include:

( [ { \ ^ $ | ) ? * + .] }  //模式中使用的所有元字符都必须`\`转义。
var exp1 = /\\n/g;  //对\n中的\转义
var exp2 = new RegExp("\\\\n","g");  // 对 \\n 再次转义

1-5, the difference between () [] {}

()  //作用是提取匹配的字符串。表达式中有几个()就会得到几个相应的匹配字符串。比如 (\s+) 表示连续空格的字符串。
[] //是定义匹配的字符范围。比如 [a-zA-Z0-9] 表示字符文本要匹配英文字符和数字。
{} //一般用来表示匹配的长度,比如 \d{3} 表示匹配三个数字,\d{1,3} 表示匹配1~3个数字,\d{3,} 表示匹配3个以上数字。

1-6, ^ and $

^ //匹配一个字符串的开头,比如 (^a) 就是匹配以字母a开头的字符串
$ //匹配一个字符串的结尾, 比如 (b$) 就是匹配以字母b结尾的字符串
^ //另一个作用就是取反,比如[^xyz] 表示匹配的字符串不包含xyz

If ^appears in [ ] it is generally negated, and elsewhere it is the beginning of the matched string.
^and $with can effectively match full strings: /d+/.test('4xpt') -> true, while /^\d+$/.test('4xpt')->false

1-7、\d \s \w . * + ?

\d 匹配一个非负整数, 等价于 [0-9]
\s 匹配一个空白字符
\w 匹配一个英文字母或数字,等价于[0-9a-zA-Z]
.  匹配除换行符以外的任意字符,等价于[^\n]
*  表示匹配前面元素0次或多次,比如 (\s*) 就是匹配0个或多个空格
+  表示匹配前面元素1次或多次,比如 (\d+) 就是匹配由至少1个整数组成的字符串
?  表示匹配前面元素0次或1次,相当于{0,1} ,比如(\w?) 就是匹配最多由1个字母或数字组成的字符串 

1-8, $1 and \1

$1-$9 存放着正则表达式中最近的9个正则表达式的提取的结果,这些结果按照子匹配的出现顺序依次排列。基本语法是:RegExp.$n ,这些属性是静态的,除了replace中的第二个参数可以省略 RegExp 之外,其他地方使用都要加上 RegExp

//使用RegExp访问
/(\d+)-(\d+)-(\d+)/.test("2016-03-26")

RegExp.$1  // 2016
RegExp.$2  // 03
RegExp.$3  // 26

//在replace中使用
"2016-03-26".replace(/(\d+)-(\d+)-(\d+)/,"$1年$2月$3日") 
// 2016年03月26日
\1 表示后向引用,是指在正则表达式中,从左往右数,第1个()中的内容,以此类推,\2表示第2个(),\0表示整个表达式。

//匹配日期格式,表达式中的\1代表重复(\-|\/|.)
var rgx = /\d{4}(\-|\/|.)\d{1,2}\1\d{1,2}"/

rgx.test("2016-03-26") //true 

rgx.test("2016-03.26") //false
 两者的区别是:\n只能用在表达式中,而$n只能用在表达式之外的地方。 

2. Regular example

//只允许输入a到z的小写字母
<input type="text" onkeyup="regExp=/[^a-z]/g;this.value=this.value.replace(regExp,'')" name="">
//只允许输入0到9的数字
<input type="text" onkeyup="regExp=/[^0-9]/g;this.value=this.value.replace(regExp,'')" name="">
//只允许输入大小写a到z和0到9的字母+数字
<input type="text" onkeyup="regExp=/[^a-zA-Z0-9]/g;this.value=this.value.replace(regExp,'')" name="">

2-2. Extract the parameter name and parameter value in the browser url, and generate a key/value object.

function getUrlParamObj(){
    var obj = {};
    //获取url的参数部分
    var params = window.location.search.substr(1);
    //[^&=]+ 表示不含&或=的连续字符,加上()就是提取对应字符串
    params.replace(/([^&=]+)=([^&=]*)/gi,function(rs,$1,$2){
        obj[$1] =  decodeURIComponent($2);
    });

    return obj;
}   //([^&=]+)=([^&=]*)/gi 每次匹配到的都是一个完整key/value,形如 xxxx=xxx, 每当匹配到一个这样的结果时就执行回调,并传递匹配到的 key 和 value,对应到$1和$2 。

2-3. Insert a new string at the specified position of the string

String.prototype.insetAt = function(str,offset){
    offset = offset + 1;
    //使用RegExp()构造函数创建正则表达式
    var regx = new RegExp("(^.{"+offset+"})");
    return this.replace(regx,"$1"+str);
};
"abcd".insetAt('xyz',2); //在c字符后插入xyz
>> "abcxyzd"
//当offset=2时,正则表达式为:(^.{3})  .表示除\n之外的任意字符,{3} 表示匹配前三个连续字符,加()就会将匹配到的结果提取出来,然后通过replace将匹配到的结果替换为新的字符串,形如:结果=结果+str

2-4. Convert the mobile phone number 12988886666 to 129****6666

function telFormat(tel){

    tel = String(tel);

    //方式一
    return tel.replace(/(\d{3})(\d{4})(\d{4})/,function (rs,$1,$2,$3){
       return $1+"****"+$3
    });

    //方式二
    return tel.replace(/(\d{3})(\d{4})(\d{4})/,"$1****$3");
}  //(\d{3}\d{4}\d{4}) 可以匹配完整的手机号,并分别提取前 3 位、4-7 位和 8-11位,"$1****$3" 是将第 2 个匹配结果用****代替并组成新的字符串,然后替换完整的手机号。

2-5. Implement HTML encoding and escape characters such as < / > ” & ` to avoid XSS attacks

on htmlEncode(str) {    //匹配< / > " & `
    return str.replace(/[<>"&\/`]/g, function(rs) {
        switch (rs) {
            case "<":
                return "<";
            case ">":
                return ">";
            case "&":
                return "&";
            case "\"":
                return """;
            case "/": 
                return "/"
            case "`":
                return "'"
        }
    });
}

3. Regular Expression Resources

Rookie Teaching : http://www.runoob.com/regexp/regexp-operator.html
w3school

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325708892&siteId=291194637