繁体   English   中英

多次重复一个正则表达式模式

[英]Repeating a regex pattern multiple times

使用JavaScript正则表达式。

我正在尝试匹配以下形式的文本块:

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

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

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

您只需要标记/g以便JavaScript Regex var re = /\\$(.*):([^$]*)/g;

正则表达式101

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

正则表达式可视化

Debuggex演示

您可以使用以下功能:

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

这个问题有一个很好的答案可以说明一切。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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