Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 484
northk Avatar asked Jan 28 '10 18:01

northk


People also ask

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

How do I match a pattern in regex?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .

How do you match numbers in JavaScript?

The \d character matches any digit which is the same as using [0-9] , the \s character matches any whitespace. However, an easier method for you would be to use the isNaN() function. If the function returns true, the number is illegal ( NaN ). If it returns false, it's a correct number.

What does \\ mean in regular expression?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \. html?\ ' .


2 Answers

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 
like image 105
Gumbo Avatar answered Oct 21 '22 21:10

Gumbo


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);
}
like image 27
Jason Orendorff Avatar answered Oct 21 '22 20:10

Jason Orendorff