将多个代码块合并在一起

时间:2018-01-16 10:29:56

标签: javascript regex

我在JS编程。我希望使用正则表达式将多个相同的“代码块”复合到一个代码块中。请注意第二个块是另一个不同的块。

示例数据

BEFORE ENTRY
  Im on the top
  block
END

RANDOM NAME
  HAHA I MAKE A PROBLEM 
END

BEFORE ENTRY
  some randon
  strings with also 1 numbers 1
END

BEFORE ENTRY
  more strings
  very cool
END

BEFORE ENTRY
  stringi
  pizza
END

期望输出

RANDOM NAME
  HAHA I MAKE A PROBLEM 
END

BEFORE ENTRY
  Im on the top
  block

  some randon
  strings with also 1 numbers 1

  more strings
  very cool

  stringi
  pizza
END

(我不关心RANDOM NAME是在顶部还是在底部。)

我失败的尝试

  1. /(?<=BEFORE ENTRY[^]*?)END[^]*?BEFORE ENTRY/g替换为""(如果在进入之前有效,则有效)

  2. /(BEFORE ENTRY)([^]*?)(END)/g\1 , \2, \3。如果我能以某种方式合并捕获组,那会有效。

  3. 关于@Archer注释的编辑:数据类型是output:内的多行字符串。

    arr = [{id:"1", output:">>EXAMPLE DATA<<"},...,{id:"n", output:">>Some similar Data<<"}]
    

2 个答案:

答案 0 :(得分:1)

编辑:抱歉,我没有看到perl标签..我应该删除答案吗?逻辑仍然可以重复使用..

如果你想使用正则表达式,我会使用更简单的第二个,并捕获组。此外,我使用一系列密钥使解决方案通用。

请注意,使用replace的函数,除了能够控制仅为第一个匹配项插入结果外,还会禁用可能位于$$的特殊替换项结果。

您没有义务将结果存储在数组中,您可以使用本地var作为结果。

var codeInput = `BEFORE ENTRY
  Im on the top
  block
END

RANDOM NAME
  HAHA I MAKE A PROBLEM 
END

BEFORE ENTRY
  some randon
  strings with also 1 numbers 1
END

BEFORE ENTRY
  more strings
  very cool
END

BEFORE ENTRY
  stringi
  pizza
END`,
  ending = 'END',
  keys = ['BEFORE ENTRY', 'RANDOM NAME'],
  i, len = keys.length, reg, match, results = {}, inserted;

for(i = 0; i < len; i++){
  //getting all the contents
  reg = new RegExp(keys[i] + '([^]*?)' + ending, 'g');
  while(match = reg.exec(codeInput)){
    if(!results[keys[i]]){
      results[keys[i]] = keys[i];
    }
    results[keys[i]] += match[1];
  }
  //inserting the result: replace the first one by result, remove others
  if(results[keys[i]]){
    results[keys[i]] += ending + '\n';
    inserted = false;
    codeInput = codeInput.replace(reg , function(){
      if(!inserted){
        inserted = true;
        return results[keys[i]];
      }
      return '';
    });
  }
}

document.getElementById('result').innerHTML = codeInput;
<pre id="result"><pre>

答案 1 :(得分:1)

使用perl

use warnings;
use strict;
my $f = 0;
my $before_entry;
while(<DATA>)
{
    $f = 1 ,  next if(/^BEFORE ENTRY/);
    print and  $f = 0 ,  if(/^END/ && $f == 2);
    $f = 0 if(/^END/);
    print and next if($f == 2);
    $f = 2  if(/^(?!BEFORE ENTRY|\s+)/ && $f != 1);
    $before_entry.=$_ if ($f == 1);
}

print "BEFORE ENTRY\n$before_entry\nEND\n"

__DATA__
BEFORE ENTRY
Im on the top
block
END

RANDOM NAME
HAHA I MAKE A PROBLEM 
END

BEFORE ENTRY
some randon
strings with also 1 numbers 1
END

BEFORE ENTRY
more strings
very cool
END

BEFORE ENTRY
stringi
pizza
END