gpt4 book ai didi

javascript - 混淆 Javascript 正则表达式与匹配函数

转载 作者:行者123 更新时间:2023-11-30 14:23:53 25 4
gpt4 key购买 nike

为什么数组中的第三个元素只是“.1”而不是“4.5.1”?我认为 \d+ 将对应于“3”,而 (\.\d)* 将捕获剩余的小数和数字。

var re = /see (chapter \d+(\.\d)*)/i;
var str = 'For more information on regular expressions, see Chapter 3.4.5.1 and CHAPTER 2.3';

console.log(str.match(re));

输出:

[ 'see Chapter 3.4.5.1',
'Chapter 3.4.5.1',
'.1',
index: 45,
input: 'For more information on regular expressions, see Chapter 3.4.5.1 and CHAPTER 2.3' ]

最佳答案

重复捕获组只会捕获其最后 重复。如果您想捕获所有的数字和句点,您应该在组内重复:

var re = /see (chapter \d+((?:\.\d)*))/i;
var str = 'For more information on regular expressions, see Chapter 3.4.5.1 and CHAPTER 2.3';

console.log(str.match(re));

如果您将原始代码插入到 regex101 中,您将看到一条描述此内容的警告:

https://regex101.com/r/uDTcTC/1

A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data

关于javascript - 混淆 Javascript 正则表达式与匹配函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52250897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com