js 正则进阶regexp

一、匹配中文,英文字母和数字及_:

const reg = /^[u4e00-u9fa5w]+$/;
const str1 = 'shangyy';
const str2 = '尚悦悦ww123'
console.log(reg.test(str1)) // true
console.log(reg.test(str2)) // true

二、贪婪匹配和惰性匹配

标识符

+?*{n}{n,}{n,m}

匹配时,如果遇到上述标识符,代表是贪婪匹配,会尽可能多的去匹配内容

// 贪婪模式(默认):

console.log('1234ab'.replace(/d{3,4}/g,'大'))
// 非贪婪模式: 量词后加?

console.log('1234ab'.replace(/d{3,4}?/g,'大'))

var str='aacbacbc';
var reg=/a.*b/;
var res=str.match(reg);
console.log(res) // aacbacb

三、断言

  • 括号是必须的,写法:(?!=...)

const num = '12345678910';
reg = /(d)(?=(d{3})+$)/g
console.log(num.match(reg)) // [ '2', '5', '8' ]
console.log(num.replace(reg, '$1,'))  // 12,345,678,910
原文地址:https://www.cnblogs.com/shangyueyue/p/10484008.html