JavaScript 正则表达式

本文详细介绍了正则表达式的创建方式、标志含义及其使用方法,包括如何进行全局匹配、粘滞匹配、忽略大小写和匹配多行等内容。此外,还列举了各种正则表达式的符号及其匹配含义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建正则表达式

1
2
3
4
5
let regExp = /a+/
// or
let regExp = new RegExp('a+')
// or
let regExp = new RegExp(/a+/, 'g')

正则标志

标志作用
g全局匹配
y粘滞匹配
i忽略大小写
m匹配多行

g标志返回多个符合正则的匹配结果

1
2
'foo bar'.match(/\w+/g)// [ 'foo', 'bar' ]
'foo bar'.match(/\w+/) // [ 'foo', index: 0, input: 'foo bar' ]

注意, 未使用g标志时,调用RegExp.exec只返回首次匹配结果

1
2
3
4
5
6
7
8
9
10
11
12
let regExp = /\w+/g
let text = 'foo bar'
console.log(regExp.exec(text)) // [ 'foo', index: 0, input: 'foo bar' ]
console.log(re.lastIndex) // 3
console.log(regExp.exec(text)) // [ 'bar', index: 4, input: 'foo bar' ]
console.log(re.lastIndex) // 7
// 对比
regExp = /\w+/
console.log(regExp.exec(text)) // [ 'foo', index: 0, input: 'foo bar' ] 
console.log(re.lastIndex) // 3
console.log(regExp.exec(text)) // [ 'foo', index: 0, input: 'foo bar' ] 
console.log(re.lastIndex) // 3

m标志匹配多行.如果使用m标志,正则表达式中的^和$将匹配每一行的开始与结束(而非整个字符串的开始和结束)

1
2
'a\nb\nc'.match(/^\w$/gm) // [ 'a', 'b', 'c' ]
'a\nb\nc'.match(/^\w$/g) // null

y标志仅在正则对象的lastIndex属性所处位置搜索

1
2
3
4
regExp = /b/y
console.log(regExp.exec('abc'))
regExp.lastIndex = 1
console.log(regExp.exec('abc'))

部分资料称y匹配失败后不会重置lastIndex属性的说法是错的

1
2
3
4
5
6
7
let regExp = /\w+/y
text = 'foo'
console.log(regExp.lastIndex) // 0
console.log(regExp.exec(text)) //  [ 'foo', index: 0, input: 'foo bar' ]
console.log(regExp.lastIndex) // 3
console.log(regExp.exec(text)) //  null
console.log(regExp.lastIndex) // 0

正则表达式符号

符号匹配示例
^匹配开始 
$匹配结束 
*匹配前一个表达式0次以上 
+匹配前一个表达式1次以上 
?匹配前一个表达式0/1次,跟在* + ? {} 后表非贪婪(默认贪婪) 
.匹配单个任意字符,换行符除外 
()捕获括号 
(?:)非捕获括号 
x(?=y)正向肯定查找,x后有y时匹配x/a(?=b)/.exec('abc')  // [ 'a', index: 0, input: 'abc' ]
x(?!y)正向否定查找,x后没有y时匹配x/a(?!c)/.exec('ab') // [ 'a', index: 0, input: 'ab' ]
(?<=y)x反向肯定查找/(?<=a)b/.exec('ab') // [ 'b', index: 1, input: 'ab' ]
(?<!x)反向否定查找/(?<!c)b/.exec('ab') // [ 'b', index: 1, input: 'ab' ]
x|y匹配x或y 
{n}匹配前一个字符n次 
{n, m}匹配前一个字符[n, m]次 
{n, }匹配前一个字符最少n次 
[xyz]匹配方括号中的任意一个字符.可使用"-"指定一个范围,方括号中的 . 和 * 无特殊意义/[a-z]/ /[\u4E00-\u9FFF ]/
[^xyz]匹配未包含在方括号中的字符/[^a-z]/
[\b]匹配退格 
\b匹配词的边界(除大小写字母 下划线 数字外的字符都被认为是边界) 
\B匹配非单词边界 
\cX? 
\d匹配数字 
\Dc非数字字符 
\f匹配换页符 
\n匹配换行符 
\r匹配回车符 
\s匹配空白字符,包括\f \n \r 等 
\S匹配非空白字符 
\t匹配制表符(Tab) 
\v匹配垂直制表符 
\w匹配一个字母/数字/下划线 
\W匹配一个非字母/数字/下划线的字符 
\n匹配之前第n个子字符串/(a)(b)\1/.exec('aba') // aba
\0匹配NULL 
\xhh匹配ASCII字符 
\uhhhh匹配unicode字符/\u6211/.exec('我们') // 我
\u{hhhh}(设置u标志时)匹配unicode字符/\u{6211}/u.exec('我们') // 我

RegExp对象方法

exec

返回数组,包含匹配的字符.未找到匹配则返回null

1
2
/(a)(b)/.exec('abc') 
// [ 'ab', 'a', 'b', index: 0, input: 'abc' ]

test

判断正则是否匹配某个字符串,返回Boolean

1
2
/(a)(b)/.test('abc')
// true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值