javascript regex exec
exec
是正则表达式的方法,用来返回匹配的字符串。
exec
的返回值
exec
的返回值是一个数组,数组的第一个元素是匹配的字符串,后面的元素是分组匹配的值。看一个列子:
1 | const str = 'There are 3 dogs, 5 cats, 2 birds and 1 cow'; |
返回值如下:
1 | [ |
循环处理
exec
通常配合while
循环使用,一边遍历,一边处理结果。注意,如果使用while循环处理,需要正则表达式中添加/g
标志。
1 | const str = 'There are 3 dogs, 5 cats, 2 birds and 1 cow'; |
输出结果:
1 | { |
/g
标志
如果想要使用while
循环来遍历所有匹配的字符串,需要使用/g
标志。否则会导致while
死循环。
match/matchAll vs exec
match
/matchAll
- 一次性返回所有匹配的字符串。exec
- 逐个返回匹配的字符串。
match
/matchAll
使用/g
时,需要对结果进行遍历。exec
是一边遍历,一边处理结果。