简体   繁体   中英

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"}]}

in javaScript and I've to extract the exact IP address --10.186.32.137 from this data

I'm trying this command--

b = aa.match(\10.186.32.137\g) but it also matches the pattern like 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?

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

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'); } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM