简体   繁体   中英

Nodejs : RegExp returns nothing

I'm trying to extract the names of electrodes and their values from the Emotiv output. However the code below returns nothing.

I'm a newbie in nodejs. I tried doing it on a single line with Regex but it's too complicated i couldn't get it right. I've succeeded in grabbing the whole line but not the values.

Here is my code :

var str = '"levels":{"F3":7094,"FC6":8209,"P7":12165,"T8":5380,"F7":1356,"F8":2043,"T7":11882,"P8":10117,"AF4":13257,"F4":6134,"AF3":13527,"O2":9686,"O1":871,"FC5":1808},"' ; 
    const reg = new RegExp('.{2}\w\"\:\d{3,5}/g'); 
    var test = str.match(reg) ; 
    if (test)   
       console.log(test[1]) ;

I expect an output to be F3 : 8209 and so on for the 14 electrodes.

I know this is not exactly answering the RegExp question but this rewrite should take get you working faster.

 const text = '"levels":{"F3":7094,"FC6":8209,"P7":12165,"T8":5380,"F7":1356,"F8":2043,"T7":11882,"P8":10117,"AF4":13257,"F4":6134,"AF3":13527,"O2":9686,"O1":871,"FC5":1808},"'; let json = "{" + text.substring(0, text.length - 2) + "}" let obj = JSON.parse(json) for (const [key, value] of Object.entries(obj.levels)) { console.log(`${key} ${value}`); } 

I've also come up with a new RegExp that I think will give you what you want.

 const text = '"levels":{"F3":7094,"FC6":8209,"P7":12165,"T8":5380,"F7":1356,"F8":2043,"T7":11882,"P8":10117,"AF4":13257,"F4":6134,"AF3":13527,"O2":9686,"O1":871,"FC5":1808},"'; let regexp = /\\"([^\\"]{2,3})\\"\\:(\\d{3,5})/g let r = null do { r = regexp.exec(text) if (r) console.log(`${r[1]} ${r[2]}`); } while (r) 

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