正则表达式解析多行字符串

时间:2017-05-04 16:28:49

标签: javascript regex

我试图解析

Mode:Managed  Frequency:2.462 GHz  Access Point: 00:00:00:00:00:00 

使用javascript正则表达式。

我的目标是获得这样的东西:

{
    Mode: 'Managed',
    Frequency: '2.462 Ghz',
    Access Point: ''
}

我试过这样的事情:

((Mode\s*):\s*)(\w+) 

但我获得了3个结果:Mode: ManagedMode:Mode。 有什么想法吗?

4 个答案:

答案 0 :(得分:1)

var str = "\
Mode:Managed  Frequency:2.462 GHz  Access Point: 00:00:00:00:00:00\n\
Mode:UnManaged  Frequency:3.462 GHz  Access Point: 00:00:00:00:00:00\n\
Mode:UnUnManaged  Frequency:4.462 GHz  Access Point: 00:00:00:00:00:00\
";

// look for some characters between "Mode:" and "Frequency:" group them as the first group
// look for some characters between "Frequency:" and "Access Point:" group them as the second group
// look for some characters after "Access Point:" group them as the third group
var regex = /Mode:\s*(.+)\s+Frequency:\s*(.+)\s+Access Point:\s*(.+)/gm;

var r, res = [];
while(r = regex.exec(str)) {
    res.push({
        "Mode": r[1].trim(),            // the first group is the Mode (trim to remove an leading or trailing spaces) 
        "Frequency": r[2].trim(),       // ...
        "Access Point": r[3].trim()     // ...
    });
}

console.log(res);

答案 1 :(得分:0)

尝试使用以下正则表达式。

正则表达式: (Mode:\S*)\s*(Frequency:\S*\s*GHz)\s*(Access Point:\s*\S*)

<强> Regex101 Demo

答案 2 :(得分:0)

  

但我获得了3个结果:Mode: ManagedMode:Mode。   有什么想法吗?

你有3个捕获组,所以你捕获了三件事。

答案 3 :(得分:0)

文本

"Mode:Managed  Frequency:2.462 GHz  Access Point: 00:00:00:00:00:00  "

正则表达式:

(.*:.*)\ {2}

结果:

  1. 模式:托管
  2. 频率:2.462 GHz
  3. 接入点:00:00:00:00:00:00