Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp Matching Hex Color Syntax (and Shorten form)

Well, I'm pretty new on regex and in particular on JavaScript regexp.

I'm looking for making a regexp that match the hex color syntax (like #34ffa6) Then I looked at the w3school page: Javascript RegExp Object

Then that's my regexp:

/^#[0-9a-f]{6}/i 

It seems to work but, if I want it to match also the "short hex color syntax" form? (like #3fa), it's possible? I've tried using the character | but maybe I'm wrong with the syntax.

like image 665
cl0udw4lk3r Avatar asked Mar 13 '12 11:03

cl0udw4lk3r


People also ask

What does \s mean in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

How do you match expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is Slash's regex?

The backslash in combination with a literal character can create a regex token with a special meaning. E.g. \d is a shorthand that matches a single digit from 0 to 9. Escaping a single metacharacter with a backslash works in all regular expression flavors.

How do you check if a hex color is valid or not?

The length of the hexadecimal color code should be either 6 or 3, excluding '#' symbol. For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.


2 Answers

/^#[0-9a-f]{3,6}$/i 

would match #abc, #abcd, #abcde, #abcdef

/^#([0-9a-f]{3}|[0-9a-f]{6})$/i 

would match #abc and #abcdef but not #abcd

/^#([0-9a-f]{3}){1,2}$/i 

would match #abc and #abcdef but not #abcd

/^#(?:[0-9a-f]{3}){1,2}$/i 

would match #abc and #abcdef but not #abcd

Have a look at RegExp - MDN to learn more about regular expressions in javascript.

like image 140
rodneyrehm Avatar answered Oct 08 '22 02:10

rodneyrehm


Try this :

/^#([0-9a-f]{6}|[0-9a-f]{3})$/i 

[0-9a-f]{6} = 6 characters [0-9a-f]{3} = 3 characters $ = end

like image 41
Manse Avatar answered Oct 08 '22 02:10

Manse