正则表达式星号用法 [英] Regex asterisk usage
问题描述
根据 MDNx* : *匹配前一项 x 0 次或更多次.*
本质上前面的字符应该是完全可选的.无论是否存在,字符串都会被匹配.那么为什么会这样:
Essentially the preceding characters should be completely optional. The string will be matched whether they exist or not. So why is it that:
1.
var text = "foobar";
var re = /q*/;
var found = text.match(re);
console.log(found); // prints '["", index: 0, input: "foobar"]'
但是
var re = /qz*/;
console.log(found); // prints 'null'
两个表达式同样不存在,因此应该匹配 0 次并且应该返回 '""'.
Both expressions equally don't exist and thus should be matched 0 times and '""' should be returned.
或者:
2.
var re = /fz*/;
console.log(found); // prints '["f", index: 0, input: "foobar"]'
但是
var re = /fzq*/;
console.log(found); // prints 'null'
这里发生了什么?根据我的理解 'fzq'
不存在所以应该匹配 0 次,并且应该返回 '""' ,对吧?如果它以某种方式匹配每个字符而不是整个字符串,'fzq*'
应该返回与 'fz'
- 'f'<相同的结果/code> 匹配一次,其余匹配 0 次.但显然这不是正在发生的事情.
What's happening here? From my understanding 'fzq'
doesn't exist so should be matched 0 times, and '""' should be returned, right? And if it somehow matches on per character basis instead of the whole string, 'fzq*'
should return the same result as 'fz'
- 'f'
is matched once and the rest is matched 0 times. But apparently this is not what's happening.
有人能解释一下这里到底发生了什么吗?
Could someone shed some light on what the hell is happening here?
推荐答案
x* : 匹配前一项 x 0 次或更多次.
在 *
被匹配零次或多次之前,你对 everything 误解了这个语句.
You misunderstood this statement with everything before *
is matched zero or more times.
当您匹配 q*
时,正则表达式将在输入字符串中搜索 q
.由于 foobar
中没有 q
,它将返回一个空字符串.
When you match q*
, the regex will search for q
in the input string. As there is no q
in the foobar
, it'll return an empty string.
当您尝试匹配 qz*
时,正则表达式将尝试在 q
<之后搜索任意数量的 z
s/强>.由于输入字符串中没有 q
,它将返回 null
.
When you try to match qz*
, the regex will try to search for any number of z
s after q
. As there is no q
in the input string, it'll return null
.
要通过 *
或任何其他量词匹配更多字符,您需要使用括号将它们分组.
To match more characters by *
or any other quantifiers, you need to group them using parenthesis.
(qz)*
这意味着,匹配字符串 qz
零次或多次.
which means, match the string qz
zero or more times.
要了解正则表达式,您可以使用 https://regex101.com/ 站点.
To understand a regex, you can use https://regex101.com/ site.
这篇关于正则表达式星号用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!