[英]JavaScript regular expressions - match a series of hexadecimal numbers
Greetings JavaScript and regular expression gurus,问候 JavaScript 和正则表达式专家,
I want to return all matches in an input string that are 6-digit hexadecimal numbers with any amount of white space in between.我想返回输入字符串中的所有匹配项,这些匹配项是 6 位十六进制数字,其间有任意数量的空格。 For example, "333333 e1e1e1 f4f435" should return an array:
例如,“333333 e1e1e1 f4f435”应该返回一个数组:
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}/);
colorValuesArray = colorValues.match(/[0-9A-Fa-f]{6}/);
Thanks for your help,谢谢你的帮助,
-NorthK -北K
Use the g flag to match globally:使用g标志进行全局匹配:
/[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:如果您愿意,还可以为不区分大小写的匹配设置i标志:
/\b[0-9A-F]{6}\b/gi
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);
}
try:尝试:
colorValues.match(/[0-9A-Fa-f]{6}/g);
Note the g
flag to Globally match.注意
g
标志全局匹配。
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
.为您提供给定字符串
subject
中所有 6 位十六进制数字的数组。
The \\b
word boundaries are necessary to avoid matching parts of longer hexadecimal numbers. \\b
字边界是必要的,以避免匹配较长的十六进制数的部分。
For people who are looking for hex color with alpha code, the following regex works:对于正在寻找带有 alpha 代码的十六进制颜色的人,以下正则表达式有效:
/\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.该代码允许带有或不带有 alpha 代码的十六进制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.