northk
northk

Reputation: 263

JavaScript regular expressions - match a series of hexadecimal numbers

Greetings JavaScript and regular expression gurus,

I want to return all matches in an input string that are 6-digit hexadecimal numbers with any amount of white space in between. For example, "333333 e1e1e1 f4f435" should return an array:

array[0] = 333333  
array[1] = e1e1e1  
array[2] = f4f435

Here is what I have, but it isn't quite right-- I'm not clear how to get the optional white space in there, and I'm only getting one match.

colorValuesArray = colorValues.match(/[0-9A-Fa-f]{6}/);

Thanks for your help,

-NorthK

Upvotes: 26

Views: 28104

Answers (6)

gignu
gignu

Reputation: 2485

Alternatively to the answer above, a more direct approach might be:

/\p{Hex_Digit}{6}/ug

You can read more about Unicode Properties here.

Upvotes: 8

Kuldeep
Kuldeep

Reputation: 537

For people who are looking for hex color with alpha code, the following regex works:

/\b[0-9A-Fa-f]{6}[0-9A-Fa-f]{0,2}\b\g

The code allows both hex with or without the alpha code.

Upvotes: 0

Jason Orendorff
Jason Orendorff

Reputation: 45086

It depends on the situation, but I usually want to make sure my code can't silently accept (and ignore, or misinterpret) incorrect input. So I would normally do something like this.

var arr = s.split();
for (var i = 0; i < arr.length; i++) {
    if (!arr[i].match(/^[0-9A-Fa-f]{6}$/)
        throw new Error("unexpected junk in string: " + arr[i]);
    arr[i] = parseInt(arr[i], 16);
}

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336148

result = subject.match(/\b[0-9A-Fa-f]{6}\b/g);

gives you an array of all 6-digit hexadecimal numbers in the given string subject.

The \b word boundaries are necessary to avoid matching parts of longer hexadecimal numbers.

Upvotes: 0

Kyle Butt
Kyle Butt

Reputation: 9780

try:

colorValues.match(/[0-9A-Fa-f]{6}/g); 

Note the g flag to Globally match.

Upvotes: 2

Gumbo
Gumbo

Reputation: 655239

Use the g flag to match globally:

/[0-9A-Fa-f]{6}/g

Another good enhancement would be adding word boundaries:

/\b[0-9A-Fa-f]{6}\b/g

If you like you could also set the i flag for case insensitive matching:

/\b[0-9A-F]{6}\b/gi

Upvotes: 34

Related Questions