Ari*_*tar 2 javascript regex string parsing extract
我正在尝试使用 Node-Red (nodered.org) 将消息传递给函数。
所以消息会是这样的:Can I have 00ff00 please?
我只对十六进制代码值感兴趣,我需要解析消息并使用正则表达式提取十六进制。这是我的代码:
var str = msg.payload;
var colorCode = str.match([A-Fa-f0-9]{6}/g);
return colorCode;
Run Code Online (Sandbox Code Playgroud)
有些事情不对劲,我收到一条错误消息Unexpected token {
[A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9]/g即使我输入错误,它也不起作用A is not defined,可能是因为它不认为它是正则表达式。
你需要把/
使用任何一个
str.match(/[A-Fa-f0-9]{6}/)或者
str.match(/[a-f0-9]{6}/i)
代替str.match([A-Fa-f0-9]{6})
现在,如果您的字符串可能包含多个十六进制代码,请改用以下内容:
str.match(/[a-f0-9]{6}/gi)-> 这将获取所有此类十六进制代码的数组,因此您可以使用数组索引访问每个此类实例,如下所示:
str="Can I have 00fA00 and B0fA0c please?"
hex_codes=str.match(/[a-f0-9]{6}/gi);
//hex_codes[0]=="00fA00" and hex_codes[1]=="B0fA0c"
Run Code Online (Sandbox Code Playgroud)
这是小提琴演示