正则表达式
创建方式
- 字面量创建
javascript
let str = "sahdjk32322nkjanls002ks"
let reg = /\d+/g
let res = str.match(reg)
- 构造函数创建
javascript
let str = "sahdjk32322nkjanls002ks"
let abc = "3232"
let reg = new RegExp(abc,"g")
let reg = new RegExp("\\d+","g") //注意对\进行转义,\变为\\
let res = str.match(reg)
匹配方法
- 正则对象下方法
- test():测试模式是否匹配,返回布尔值
- exec():查找匹配项,返回包含第一个匹配信息的数组,没有返回null
- lastIndex:表示下一次搜索开始的位置,在全局模式下,执行exec()后会改变
- 字符串方法
- spilt()
- search()
- match()
- replace()
元字符
有特殊函数非字母字符
- 字符相关
- \w:数字、字母、下划线
- \W:非数字、字母、下划线
- \d:数字
- \D:非数字
- \s:匹配空格
- \S:非空格
- . :非\n \r \u2028 \u2029
- 数量相关
- { }:表示出现多少次
javascript
let reg = /ce{3}f/g
let reg = /ce{1,4}f/g //闭区间
let reg = /ce{1,}f/g //1到无限
- ?:
- +:
- *:
- 默认是贪婪匹配
- 加?变成惰性匹配
javascript
let str = "123456789"
let reg = /\d{2,4}/g
str.match(reg)
//["1234","5678"]
let reg = /\d{2,4}?/g
str.match(reg)
//["12","34","56","78"]
- 位置相关
- ^:首位
javascript
let str = "shdjssa"
let reg = /^\w/g
str.replace(reg,"*")
//*hdjssa
let reg = /^/g
str.replace(reg,"*")
//*shdjssa
- $:末位
- \b:边界符(非\w的都是边界)
javascript
let str = "this is a book"
let reg = /\bis\b/g
str.match(reg)
//第二个is
- \B:非边界
javascript
let str = "this is a book"
let reg = /\Bis\b/g
str.match(reg)
//第一个is
- 括号相关
- ( ):分组、提取值 、替换、反向引用
javascript
let str = "2021-07-20"
let reg = /(\d{4})-(\d{2})-(\d{2})/g
str.match(reg)
console.log(RegExp.$1) //2021
console.log(RegExp.$1) //07
console.log(RegExp.$1) //20
str.replace(reg,"$2/$3/$1b")
//反向引用
let className = "news-container-nav" //或者"news_container_nav"
let reg = /\w{4}(-|_)\w{9}(\1)\w{3}/g // (\1)表示引用第一个分组
- $:提取值
- [ ]:字符集合
javascript
let str = "My name is LiLei" //或者Lilei
let reg = /Li[Ll]ei/g
[a-z],[A-Z],[0-9]
[^0-9] //非数字
\w == [a-zA-Z0-9_]
匹配模式
g:全局匹配
i:忽略字母大小写
m:多行模式
javascriptlet str = `abc efg hij` let reg = /^\w/gm; str.replace(reg,"*") //*bc //*fg //*ij
s:让 "."能匹配到换行
javascript
let str = `abc
efg`
let reg = /^a.*g$/gs;
str.replace(reg,"*")
- u:匹配unicode编码
javascript
let str = "a" //a的Unicode编码为61
let reg = /\u{61}/gu
- y:粘性模式
javascript
let str = "12345asdhksj345"
let reg = /\d/g
//只能匹配12345,不能匹配后面阿345
命名分组
javascript
let str = "2021-07-20"
let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g
str.match(reg)
零宽断言
- 正向零宽断言
javascript
let str = "iphone3iphone4iphone5iphonenumber"
//肯定
let reg = /iphone(?=\d)/g
let res = str.replace(reg,"苹果")
//苹果3苹果4苹果5iphonenumber
//否定
let reg = /iphone(?=!\d)/g
let res = str.replace(reg,"苹果")
//苹果3苹果4苹果5iphonenumber
- 负向零宽断言
javascript
let str = '10px20px30pxipx'
//肯定
let reg = /(?<=\d+)px/g
let res = str.replace(reg,"像素")
//否定
let reg = /(?<!\d+)px/g
let res = str.replace(reg,"像素")