匹配任何开头为 n 的字符串。注意 /[^a] / 和 /^ [a]/是不一样的,前者是排除的,后者是代表首位。
(?=n)
匹配任何其后紧接指定字符串 n 的字符串。正向预查
(?!n)
匹配任何其后没有紧接指定字符串 n 的字符串。反向预查
RegExp 对象方法
test()
test() 方法检索字符串中是否存在指定的值。返回值是 true 或 false。
1 2 3 4 5 6 7 8 9 10 11
//判断是不是QQ号 //首位不能是0 //必须是5-11位数的数字
var str = '812634676'; var regexp = /^[1-9][0-9]{4,10}$/gim; if (regexp.test(str)){ alert('is'); }else{ alert('no'); }
exec()
exec() 方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。
1 2 3 4 5 6 7
var patt1 = newRegExp('e'); console.log(patt1.exec('some text')); //OUTPUT:e
var patt2 =newRegExp('ee'); console.log(patt2.exec('some text')); //OUTPUT:null
compile()
compile() 既可以改变检索模式,也可以添加或删除第二个参数。
1 2 3 4 5 6
var patt1=newRegExp("e"); document.write(patt1.test("The best things in life are free")); // true // 改变了检索模式 patt1.compile("eee"); document.write(patt1.test("The best things in life are free")); // false
支持正则表达式的String对象的方法
search 检索与正则表达式相匹配的值。
1 2 3
var str = "Visit W3School!"; console.log(str.search(/W3School/)) // OUTPUT:6
replace替换与正则表达式匹配的子串。
1 2 3
var str = "Visit Microsoft!"; console.log(str.replace(/Microsoft/,"W3School")); // OUTPUT:Visit W3School!