多次重复正则表达式

时间:2014-12-30 19:20:56

标签: javascript regex

使用JavaScript regexes。

我正在尝试匹配表单中的文本块:

$Label1: Text1
    Text1 possibly continues 
$Label2: Text2
$Label3: Text3 
     Text3 possibly continues

我想分别捕捉标签和文字,以便我最终得到

["Label1", "Text1 \n Text1 possibly continues", 
 "Label2", "Text2", 
 "Label3", "Text3 \n Text3 possibly continues"]

我有一个与模式的单个实例匹配的正则表达式\$(.*):([^$]*)

我想也许是这样的:(?:\$(.*):([^$]*))*会给我想要的结果,但到目前为止我还没有弄清楚有效的正则表达式。

2 个答案:

答案 0 :(得分:2)

您只需要标记/g,因此JavaScript正则表达式var re = /\$(.*):([^$]*)/g;

Regex101

\$(.*):([^$]*)

Regular expression visualization

Debuggex Demo

答案 1 :(得分:1)

您可以使用以下功能:

function extractInfo(str) {
    var myRegex = /\$(.*):([^$]*)/gm; 
    var match = myRegex.exec(str);
    while (match != null) {

      var key = match[1];
      var value = match[2];
      console.log(key,":", value);
      match = myRegex.exec(str);
}}  

使用您的示例,

var textualInfo = "$Label1: Text1\n    Text1 possibly continues \n$Label2: Text2\n$Label3: Text3 \n     Text3 possibly continues";
extractInfo(textualInfo);

结果:

[Log] Label1 :  Text1
    Text1 possibly continues 

[Log] Label2 :  Text2

[Log] Label3 :  Text3 
     Text3 possibly continues

有一个很好的答案to this question可以解释这一切。