简体   繁体   English

js正则表达式量词和全局标志输出空字符串作为匹配数组中的最后一个元素

[英]js regex quantifiers and global flag outputs empty string as the last element in the matched array

I have: 我有:

var str = 'ddd';
var r = /d*/g;
console.log(str.match(r))

the output in my console is an array of two; 我的控制台中的输出是两个数组; first is a string containing 'ddd' and second its a empty string. 第一个是包含'ddd'的字符串,第二个是一个空字符串。 I know what * means (0 or more) but why it outputs that empty string? 我知道*意思是(0或更多),但是为什么它输出那个空字符串呢? I would expect to ouptut just one string 'ddd' . 我希望仅输入一个字符串'ddd' Once it matches for d key, why it just continue with that empty string? 一旦与d键匹配,为什么只继续输入该空字符串?

If I call without the g flag, it outputs what I really expected to do with it. 如果我在没有g标志的情况下进行调用,它将输出我真正希望它执行的操作。

I also know that g means, global search, it iterates through all elements of str , but how that, when my search was completed by the first match? 我还知道g意味着全局搜索,它会遍历str所有元素,但是当我的搜索在第一个比赛中完成时,那又如何呢?

The pattern d* means "zero or more occurrences of 'd'". 模式d*表示“ d*零次或多次出现”。 Zero occurrences of 'd' is the empty string. 零出现的'd'是空字符串。 The greedy * first matches all the 'd' characters in the string, and then matches the nothing between the last 'd' and the end of the string. 贪婪*首先匹配字符串中的所有'd'字符,然后匹配最后一个'd'和字符串结尾之间的所有字符。

The g flag on the pattern tells the regular expression matching mechanism to iteratively re-try the match. 模式上的g标志指示正则表达式匹配机制迭代地重试匹配。 The first iteration matches all of the 'd' characters. 第一次迭代匹配所有“ d”字符。 At that point, the remaining string is basically the empty string; 那时,剩下的字符串基本上就是空字符串。 a string with zero length. 长度为零的字符串。 The match succeeds in the same way that "".match(/d*/g) would succeed. 匹配成功的方式与"".match(/d*/g)成功的方式相同。

It's logical that you got two matches here: 逻辑上您在这里有两场比赛:

  • First one is 'ddd' : 第一个是'ddd'

    which is logical with d* . d*逻辑d*

  • Second one is ' ' : 第二个是''

    which is logical too with d* , because the * means zero or many times and that's zero d here, and it's not a white space, just an empty string so basically any string will be matching it. 这对于d*也是合乎逻辑的,因为*表示零或很多次,这里的d等于零,并且它不是空格,只是一个空字符串,因此基本上任何字符串都可以匹配它。

You should have been using d+ instead. 您应该一直使用d+

EDIT: 编辑:

You can see it in this DEMO that with ddd the matches are: 您可以在此演示中看到,使用ddd的匹配是:

  1. [0-3] ddd [0-3] ddd

  2. [3-3] `` [3-3]``

It's taking the last of the string as a match here with the index : [3-3] 它使用字符串的最后一个作为与索引的匹配: [3-3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM