【问题标题】:Repeating a regex pattern multiple times多次重复正则表达式模式
【发布时间】:2014-12-30 19:20:55
【问题描述】:

使用 JavaScript 正则表达式。

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

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

我想分别捕获标签和文本,这样我就会得到 ​​p>

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

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

我想可能是这样的:(?:\$(.*):([^$]*))* 会给我想要的结果,但到目前为止我还没有找到一个有效的正则表达式。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您只需要标志 /g 所以 JavaScript 正则表达式 var re = /\$(.*):([^$]*)/g;

    Regex101

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

    Debuggex Demo

    【讨论】:

    • /\$(.*):([^$]*)/g 匹配会产生一个只有两个值的数组,['$Label1: Text1 \n Text1 possibly continues ', '$Label2: Text2 $Label3: Text3 Text3 possibly continues' ]。这是否意味着我原来的正则表达式是错误的?
    • @Jephron 不,你的正则表达式是正确的,只需要循环匹配。
    【解决方案2】:

    您可以使用以下功能:

    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 可以解释一切。

    【讨论】:

      猜你喜欢
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      相关资源
      最近更新 更多