正则基础
正则的组成
元字符:在正则中有特殊意义的字符都是元字符。
-
特殊字符
\:转义字符^:以什么开头$:以什么结尾.:匹配除了\n之外的任意字符 -
量词元字符
*:前面的表达式出现 0 到多次?:前面的表达式出现 0 到 1 次+:。。。出现 1 到多次{n}:。。。出现 n 次{n,}:。。。至少出现 n 次{n,m}:。。。出现 n 到 m 次 -
其他
x | y: x 或 y 中的一个[xyz]: xyz 中任意一个字符[^xyz]: 除了 xyz 任意一个其他字符[a-z]: a 到 z 中任意一个字符[^a-z]: 除了 a 到 z 的字符\b: 匹配单词边界\B: 匹配一个非单词边界\d: 0-9 数字\D: 除了 0-9 之外的字符\n: 匹配一个换行符\w:[a-zA-Z0-9_]\W:[^a-zA-Z0-9_]修饰符:g–globali–ignoreCasem–multiline
创建正则
-
字面量方式
var reg = /\d/g; -
构造函数
var reg = new RegExp("\\d", "g"); var str = "hello"; reg = new RegExp("\\d" + str + "+", "g"); //可以引入变量 // 相当于 reg = /\dhello+/g;
正负向预查
-
正向预查
(?=pattern)匹配pattern但不获取匹配结果。?=表达式必须跟着括号中内容,在捕获时不对括号中的内容进行捕获var reg = /hello(?=world!)/; reg.exec("helloworld!"); //["hello",index:0,input:"helloworld!"] -
负向预查
(?!pattern)不匹配pattern且不获取匹配结果。var reg = /hello(?!world!)/; reg.exec("helloworld!"); //null console.log(reg.exec("helloorld!")); //["hello", index: 0, input: "helloorld!"] -
(?:pattern)var reg = /hello(?:world!)/; console.log(reg.exec("helloworld!")); //["helloworld!", index: 0, input: "helloworld!"] reg = /windows(?=95|98)/; console.log(reg.exec("windows98")); //["windows", index: 0, input: "windows98"] reg = /hello(?!world!)/; console.log(reg.exec("helloworld!")); //null console.log(reg.exec("helloorld!")); //["hello", index: 0, input: "helloorld!"]
正则分组
() 改变了正则中的优先级,\1代表和第一个分组出现一模一样的内容
var reg = /^(\w)(\d)\2\1$/;
console.log(reg.test("ab")); // false
console.log(reg.test("a11a")); // true
console.log(reg.test("a1a")); // false
懒惰性
var reg = /\d+/;
reg.exec("hello123world234"); //第一次捕获123 第二次还是捕获123
//g 修饰符可以解决懒惰性: 每一次捕获,都改变正则属性lastIndex的属性值,属性值是下一次开始的索引位置;当下一次捕获时,开始的索引位置是上一次捕获的结束位置索引的下一个
reg = /\d+/g;
reg.exec("hello123world234"); //第一次捕获123 第二次还是捕获1234
贪婪性
var reg = /\d+/g;
reg.exec("hello123world234"); //第一次获取123,如果想每次只取一个数字,需要消除贪婪性:把?加到量词元字符后边
reg = /\d+?/g;
reg.exec("hello123world234"); //第一次捕获1,第二次2,依次。。。