Nodejs:RegExp不返回任何内容

时间:2019-04-04 22:17:00

标签: javascript node.js regex parsing

我正在尝试从Emotiv输出中提取电极的名称及其值。但是,下面的代码不返回任何内容。

我是nodejs的新手。我尝试使用Regex在同一行上执行此操作,但是它太复杂了,我无法正确执行。我已经成功地抓住了整条线,但没有抓住价值。

这是我的代码:

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]) ;

我希望14个电极的输出为F3 : 8209,依此类推。

1 个答案:

答案 0 :(得分:0)

我知道这不能完全回答RegExp问题,但是这种重写应该可以使您更快地工作。

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

我还提出了一个新的RegExp,我想它将为您提供想要的东西。

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)