Why does regex not match when there are more then one #?
I just came across the following function below:
function hexToRgb(hex){
// By Tim Down - http://stackoverflow.com/a/5624139/3493650
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-fd])([a-fd])([a-fd])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
Now I tried the following regex in my browser console:
s = "#ddd"
s.match(/^#?([a-fd])([a-fd])([a-fd])$/i) // RESULT ["#ddd", "d", "d", "d"]
Now when I change s
to the following:
s = "##ddd"
s.match(/^#?([a-fd])([a-fd])([a-fd])$/i) // null
Why is it null? Why no match, when I check the regex in the regex checker here :
It says the following:
#? matches the character # literally Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy]
Now the above statement says as many times as possible , so why does ##fff
not match with the regex /^#?([afd])([afd])([afd])$/i
?
The explanation given by Regex101 can be misunderstood. I would rewrite it as
"Between zero and one time, preferably one, but also allowing zero if necessary (greedy)"
In general, greedy matching means "try to match as many as possible", but in this case the maximum allowed number is 1
.
^#?([a-fd])
means
#
. This obviously fails with ##1
(and this isn't affected by laziness or greediness in this case).
You needed the +
:
^#+?([afd])([afd])([afd])$
The +
matches 1 or more of the preceding token.
The ?
makes the preceding quantifier lazy, causing it to match as few characters as possible.
Edit:
It can actually be simplified to ^#+([afd])([afd])([afd])$
since as @TimPietzcker mentioned, the following tokens can't match #
.
You need a '+' after your hash.
With '+' The preceding item will be matched one or more times.
You regex will be ^#+?([afd])([afd])([afd])$
上一篇: 正则表达式贪婪的解析方向
下一篇: 为什么正则表达式在不止一个#时不匹配?