常用正则表达式
1.数字,保留两位小数
1
| ^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})?$
|
1 2 3 4
| 2.22, true 2.0 true 2 true 2.222 false
|
1.1.有效数字,不以0结尾
1
| let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d*[1-9]+)?$/;
|
1 2 3 4
| 2.20 false 2.22 true 2 true 2.222 true
|
2.连续相同字符
1 2 3
| let s = "aaabbcde" s.match(/(.)\1*/g); ["aaa","bb","c","d","e"]
|
3.奇数
4.以某个字符开头的字符
1 2
| onst reg = new RegExp(`(?<=${str})\\w+`, 'g'); (?<=${str}) 以某个字符开头
|
方法
1.replace
语法
str.replace(regexp|substr, newSubStr|function)
1 2
| let ex = "aadcd"; ex = ex.replace('a',1) // "1adcd"
|
1 2
| let ex = "aadcd"; ex = ex.replace(/a/g,1) // "11dcd"
|
1 2 3 4 5 6 7 8
| let obj = {a: 1, b: 2} let ex = "aadcd"; ex = ex.replace(/a/g, (match ,offset) => { console.log(match) // 匹配对象 console.log(offset) // 下标 return obj[match] }) console.log(ex) // "11dcd"
|
2.replaceAll
ES2021新特性-替换一个字符串中的所有指定字符 replaceAll()方法的使用
String.protype.replaceAll
在 ES2021 之前
1 2 3
| const str = '2-4-6-8-10'; const newStr = str.replace(/\-/g, '+'); console.log(newStr);
|
ES2021 之后:
1 2 3
| const str = '2-4-6-8-10'; const newStr = str.replaceAll('-', '+'); console.log(newStr); //2+4+6+8+10
|
在正则中使用变量
1 2
| let pre = "flo" let reg = new RegExp(`${pre}`)
|
基础知识
正则只能用于匹配,不能用于计算
1 2 3 4 5 6 7 8 9
| .匹配除换行符以外的任意字符 \w 匹配字母或数字或下划线或汉字 等价于 ‘[A-Za-z0-9_]’。 \s 匹配任意的空白符 \d 匹配数字 + 表示重复一次或者多次 ?表示重复0次或1次(最多1次); * 表示重复零次或者多次 {n,m} 表示n 到 m 次 /\XX/g 全局替换
|