10.19.JS-正则

248 阅读1分钟

RegExp

  • 直接量(推荐使用)
  • new RegExp();
  • i(ignoreCase)、g、m
  • \w === [0-9A-z_]
  • \W === [^\w]
  • \d === [0-9]
  • \D === [^\d]
  • \s === [\t\n\r\v\f]
  • \S === [^\s]
  • unicode码
 var reg = /\u4f60\u597d/g;
var str = '你好';
console.log(str.match(reg));

量词

// n+ {1, }
// n* {0, }
// n? {0,1}
// n{X} {X}
// n{x,y} {x,y}
// n{x, } {x, }
// 通过 ^$ 限制开头结尾
// var reg = /\w*/g;
// var str = "abc";
// console.log(str.match(reg)); // [ 'abc', '' ] 逻辑上先匹配了 "abc" 在之后匹配第0位
// var reg = /\d*/g;
// console.log(str.match(reg)); // [ '', '', '', '' ]
// 匹配原则:贪婪匹配原则
// https://www.w3school.com.cn/jsref/jsref_obj_regexp.asp
// var reg = /^abc$/g;
// var str = "abc";
// console.log(str.match(reg));

检验一个字符串首尾是否含有数字

// 首含有数字 或 尾含有数字
var reg = /^\d[\s\S]*\d$/g; // 首尾都含有数字
var reg2 = /^\d|\d$/g; // 首或尾含有数字
var str = "123abc1";
console.log(reg.test(str)); // true 

正则属性

  • lastIndex(最重要) global ignoreCase multiline source

exec()

// reg.exec()
// 游标变化
var reg = /ab/g;
var str = 'abababab';
console.log(reg.lastIndex); // 0
console.log(reg.exec(str)); // [ 'ab', index: 0, input: 'abababab']
console.log(reg.lastIndex); // 2
console.log(reg.exec(str)); // [ 'ab', index: 2, input: 'abababab']
console.log(reg.lastIndex); // 4
console.log(reg.exec(str)); // [ 'ab', index: 4, input: 'abababab']
console.log(reg.lastIndex); // 6
console.log(reg.exec(str)); // [ 'ab', index: 6, input: 'abababab']
console.log(reg.lastIndex); // 8
console.log(reg.exec(str)); // null
console.log(reg.lastIndex); // 0
// 正则不添加g,lastIndex一直从零开始

匹配四个相同的值

var str = "aaaa";
var reg = /(\w)\1\1\1/g; // \1反向引用第一个子表达式引用的内容
console.log(reg.test(str));

匹配aabb的值

var str = 'aabb';
var reg = /(\w)\1(\w)\2/g; // \1反向引用第一个子表达式引用的内容
console.log(reg.test(str));

字符串对象方法

// 正则不添加g, match返回类似exec(), 添加g,match返回数组
// search 返回目录
// split
// replace 最常用

replace

var str = "aaaa";
console.log(str.replace("a", "b")); // 只能匹配一个 baaa

var reg = /a/g;
console.log(str.replace(reg, 'b')); // bbbb */

var reg = /(\w)\1(\w)\2/g;
var str = "aabb";
console.log(str.replace(reg, "$2$2$1$1"));

var reg = /(\w)\1(\w)\2/g;
var str = "aabb";
console.log(str.replace(reg, function ($, $1, $2) {
  return $2 + $2 + $1 + $1 + "abc"; // "bbaaabc"
}));

the-first-name -> theFirstName

var reg = /-(\w)/g;
var str = "the-first-name";
console.log(str.replace(reg, function ($, $1) {
  return $1.toUpperCase();
})); // theFirstName

正向预查 正向断言

var str = "abaaaa";
var reg = /a(?=b)/g; // a?=b a后面跟着b, 不参与选择, 只参与修饰 ; a?!b , a后面不跟着b
console.log(str.match(reg)); // [ 'a' ]

非贪婪匹配, ? 打破贪婪匹配

var reg = /a+?/g; // 能取1不取1+

正则去重

var str = "aaaaaaabbbbbbbcccccc";
var reg = /(\w)\1*/g;
console.log(str.replace(reg, "$1")); // abc