gpt4 book ai didi

javascript - 当我期望一个匹配时,match() 返回包含两个匹配的数组

转载 作者:可可西里 更新时间:2023-11-01 01:21:50 24 4
gpt4 key购买 nike

考虑以下示例:

<html>
<body>

<script type="text/javascript">

var str="filename.jpg";

var pattOne = new RegExp('\.[^\.]*$');
var pattTwo = new RegExp('(\.[^\.]*$)');
var pattThree = new RegExp('(\.[^\.]*$)', 'g');

document.write(str.match(pattOne));
document.write('<br>');
document.write(str.match(pattTwo));
document.write('<br>');
document.write(str.match(pattThree));

</script>
</body>
</html>

结果如下:

.jpg
.jpg,.jpg
.jpg

我期望这样的结果:

.jpg
.jpg
.jpg

为什么在正则表达式两边加上括号会改变结果?为什么使用 'g' 修饰符再次改变结果?

最佳答案

来自 String.prototype.match [MDN] :

If the regular expression does not include the g flag, returns the same result as regexp.exec(string).

哪里RegExp.prototype.exec documentation [MDN]说:

The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.

因此,当您在第二个表达式中引入捕获组时,第一个元素是整个匹配项,第二个元素包含捕获组的内容,在您的示例中,它也是整个匹配项。
第一个表达式没有捕获组,因此您只能取回匹配项。

回到匹配文档:

If the regular expression includes the g flag, the method returns an Array containing all matches. If there were no matches, the method returns null.

使用g修饰符,只返回匹配项,不返回捕获组的内容。在您的字符串中只有一个匹配项。

关于javascript - 当我期望一个匹配时,match() 返回包含两个匹配的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9002771/

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