解释
预查又称环视(Lookaround)、属于零宽断言(Zero-Length Assertions)的一种,有 4 个语法:
语法 | 中文名 | 英文名 |
---|---|---|
(?=regex) | 肯定性前瞻 | Positive lookahead |
(?!regex) | 否定性前瞻 | Negative lookahead |
(?<=regex) | 肯定性后顾 | Positive lookbehind |
(?<!regex) | 否定性后顾 | Negative lookbehind |
比拟艰深的解释:
- 肯定性:匹配
regex
- 否定性:不匹配
regex
- 前瞻:向前(右、正向)看(预查)
- 后顾:向后(左、反向)看(预查)
- 肯定性前瞻:先看看后面(左边)是否匹配
regex
,但不向前走 - 否定性前瞻:先看看后面(左边)是否不匹配
regex
,但不向前走 - 肯定性后顾:回头看前面(右边)是否匹配
regex
- 否定性后顾:回头看前面(右边)是否不匹配
regex
利用
1、判断是否同时蕴含但不限于大写字母、小写字母和数字,且不能蕴含 114514
,长度为 8~32 个字符
/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?!.*114514).{8,32}$/.test('10086@qq.COM')// true
2、判断不以 80
、82
、84
、86
、88
结尾
/^(?!8[02468])\d+$/.test('81789110')// true
3、匹配由空白宰割的字符串中的纯数字串
'123 abc 1st\r\n4 1970\'s 56 @10086 789'.match(/(?<!\S)\d+(?!\S)/g)// ['123', '4', '56', '789']'123 abc 1st\r\n4 1970\'s 56 @10086 789'.match(/(?<=^|\s)\d+(?=\s|$)/g)// ['123', '4', '56', '789']
4、仅删除夹在数字中的逗号
'And then, I have 1,003,334, you have 996,6,6,6'.replace(/(?<=\d),(?=\d)/g, '')// 'And then, I have 1003334, you have 996666'
5、在数字中增加分组逗号
'And then, I have 1003334, you have 996666'.replace(/(?<=\d)(?=(?:\d{3})+(?!\d))/g, ',')// 'And then, I have 1,003,334, you have 996,666'
6、判断是否仅蕴含字母,但不蕴含小写元音字母
/^(?:(?![aeiou])[A-Za-z])+$/g.test('src')// true/^(?=[A-Za-z]+$)[^aeiou]+$/g.test('src')// true
7、判断是否是字母或数字或字母+数字,不能为空
/^(?=.)[a-z]*\d*$/i.test('Add1')// true
8、匹配长度为 11 的号码,留神不能是其余号码的子串
`name:123456789id:11012345678910tel:12345678910name:abc11111111111id:888888888888tel:11966`.match(/(?<!\d)\d{11}(?!\d)/g)// ['12345678910', '11111111111']
9、如果短少协定前缀,则增加 http://
,疏忽空行
String.raw`segmentfault.com//bing.com\baidu.com127.0.0.1ftp://127.0.0.1https://google.com`.replace(/^(?![a-z]+:)[\\/]*(?=.)/gim, 'http://')/*http://segmentfault.comhttp://bing.comhttp://baidu.comhttp://127.0.0.1ftp://127.0.0.1https://google.com*/