-
空格匹配
let pattern = /goo gle/; //直接使用空格匹配 let str = 'goo gle'; alert(pattern.test(str));
let pattern = /goo\sgle/; //\s表示空格匹配 let str = 'goo gle'; alert(pattern.test(str));
-
\b表示到达边界
let pattern = /google\b/; let str = 'google'; alert(pattern.test(str));
-
|表示匹配或选择模式
let pattern = /google|baidu|bing/; let str = 'this is a bing'; alert(pattern.test(str));
-
a{n,m}标识a的n至m次
let pattern = /google{4,8}$/; //表示e的4-8次 let str = 'googleeee'; alert(pattern.test(str));
let pattern = /(google){4,8}$/; //分组,可以看成一个字符 let str = 'googlegooglegooglegoogle'; //表示google4-8次 alert(pattern.test(str));
let pattern = /8.*8/; let str = 'This is a 8google8'; alert(pattern.test(str));
let pattern = /8(.*)8/; let str = 'This is a 8google8'; str.match(pattern); alert(RegExp.$1);
-
$1
//RegExp.$1表示获取模式中第一个分组对应的匹配字符串 //$1表示分组获取字符串匹配到的内容 let pattern = /8(.*)8/; let str = 'This is a 8google8'; document.write(str.replace(pattern, '<strong>$1</strong>'));
-
位置交换
let pattern = /(.*)\s(.*)/; let str = 'google baidu'; alert(str.replace(pattern, '$2 $1'));
let pattern = /[a-z]+/; //这里使用了贪婪模式 let str = 'abcdefj'; alert(str.replace(pattern, '1')); //所有的字符串变成了1
//使用惰性模式 let pattern = /[a-z]+?/; let str = 'abcdefj'; alert(str.replace(pattern, '1')); //只有第一个字符变成了1,后面没有匹配
//开启全局,并且使用惰性模式 let pattern = /[a-z]+?/g; let str = 'abcdefj'; alert(str.replace(pattern, '1')); //每一个字母替换成了1
//使用了贪婪, let pattern = /8(.*)8/; let str = '8google8 8google8 8google8'; //匹配到了google8 8google8 8google document.write(str.replace(pattern, '<strong>$1</strong>')); //结果:<strong>google8 8google8 8google</strong>
//使用了惰性,开启全局 let pattern = /8(.*?)8/g; let str = '8google8 8google8 8google8'; document.write(str.replace(pattern, '<strong>$1</strong>')); //这次结果正确了 //<strong>google</strong> //<strong>google</strong> //<strong>google</strong>
//另一种惰性,屏蔽了8的匹配,也就是两边包含字符 let pattern = /8([^8]*)8/g; let str = '8google8 8google8 8google8'; document.write(str.replace(pattern, '<strong>$1</strong>')); //<strong>google</strong> //<strong>google</strong> //<strong>google</strong>
网友评论