[英]How to extract a IP address from JavaScript string data
I have string data aa = {"PC-lab-network-452":[{"version":4,"addr":"10.186.32.137","OS-EXT-IPS:type":"fixed","OS-EXT-IPS-MAC:mac_addr":"fa:16:3e:39:38:ac"}]}我有字符串数据 aa = {"PC-lab-network-452":[{"version":4,"addr":"10.186.32.137","OS-EXT-IPS:type":"fixed"," OS-EXT-IPS-MAC:mac_addr":"fa:16:3e:39:38:ac"}]}
in javaScript and I've to extract the exact IP address --10.186.32.137 from this data在 javaScript 中,我必须从该数据中提取确切的 IP 地址 --10.186.32.137
I'm trying this command--我正在尝试这个命令——
b = aa.match(\10.186.32.137\g) but it also matches the pattern like 10.186.32.13. b = aa.match(\10.186.32.137\g) 但它也匹配像 10.186.32.13 这样的模式。 I need to match the exact pattern.我需要匹配确切的模式。 Any help to fix this?有什么帮助解决这个问题吗?
One of the most simple regex pattern would be:最简单的正则表达式模式之一是:
const aa = `{"PC-lab-network-452":[{"version":4,"addr":"10.186.32.137","OS-EXT-IPS:type":"fixed","OS-EXT-IPS-MAC:mac_addr":"fa:16:3e:39:38:ac"}]}` const reg = new RegExp(/..\....\...\..../g) const res = aa.match(reg) console.log(res[0]);
but as posted in comments why not use JSON.parse?但正如评论中所说,为什么不使用 JSON.parse?
Parse the string with JSON.parse(STRING) then access your network object ("PC-lab-network-452") JSON.parse(aa)["PC-lab-network-452"]
then access any valid array index JSON.parse(aa)["PC-lab-network-452"][0]
then access the addr
property JSON.parse(aa)["PC-lab-network-452"][0].addr
Parse the string with JSON.parse(STRING) then access your network object ("PC-lab-network-452") JSON.parse(aa)["PC-lab-network-452"]
then access any valid array index JSON.parse(aa)["PC-lab-network-452"][0]
然后访问addr
属性JSON.parse(aa)["PC-lab-network-452"][0].addr
If you want to solve this without regex.如果你想在没有正则表达式的情况下解决这个问题。 Try this:尝试这个:
const a = {"PC-lab-network-452":[{"version":4,"addr":"10.186.32.137","OS-EXT-IPS:type":"fixed","OS-EXT-IPS-MAC:mac_addr":"fa:16:3e:39:38:ac"}]}; Object.keys(a).forEach(item => { const ipExist = a[item].find(obj => obj.addr === "10.186.32.137"); if (ipExist) { console.log(ipExist.addr); } else { console.log('IP not found'); } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.