Write a regexp to describe a web-color, which starts with ‘#’ followed by 3 or 6 hexadimal chars.
var re = /*...your global regexp...*/ var subj = "color: #3f3; background-color: #AA00ef" alert( subj.match(re) ) // #3f3,#AA00ef
Решение, шаг 1
Решение
Решение, шаг 1
The regular expression for 3-char colors is: /#[a-f0-9]{3}/i.
You need to add another 3-char part, making it optional.
Решение, шаг 2
Решение, шаг 2
To make 6 characters also possible, we allow the color code part to repeat 2 times:
/#([a-f0-9]{3}){1,2}/i.
We have to put brackets outside of [a-f0-9]{3}, because the quantifier {1,2} applies to whole this structure as a group.
The regexp above can be rephrased as a longer, but maybe simpler variant:
/#[a-f0-9]{3}([a-f0-9]{3})?/i
It reads as a 3-character color, optionally followed by 3 more characters.
Finally, the test:
var re = /#([a-f0-9]{3}){1,2}/gi
var subj = "color: #3f3; background-color: #AA00ef"
alert( subj.match(re) ) // #3f3,#AA00ef
#256