match()返回包含两个匹配项的数组,而我期望一个匹配项

match() returns array with two matches when I expect one match

本文关键字:期望 一个 数组 返回 match 包含两      更新时间:2023-09-26

考虑以下示例:

<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]:

如果正则表达式不包含g标志,则返回与regexp.exec(string)相同的结果。

其中RegExp.prototype.exec文档[MDN]表示:

返回的数组将匹配的文本作为第一项,然后为每个匹配的包含捕获的文本的捕获括号提供一项。

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

返回match文档:

如果正则表达式包含g标志,则该方法返回一个包含所有匹配项的数组。如果没有匹配项,则该方法返回null

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

.match()函数返回一个数组。document.write()将数组打印为字符串。

当你在字符串中捕获一个组时,它会生成一个像这样的数组:

Array(
  [0] => 'the complete matched string',
  [1] => 'the first captured group',
  [2] => 'the second captured group', 
  [.] => '...'
)

因此,使用正则表达式,它变成:

Array(
  [0] => '.jpg', // You match .jpg of the string
  [1] => '.jpg' // You captured the .jpg match
)

如果打印一个数组,它会在值之间放置一个,