[英]merging multiple code blocks together
我在用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
(我不在乎“隨機名稱”在頂部還是底部。)
/(?<=BEFORE ENTRY[^]*?)END[^]*?BEFORE ENTRY/g
替換為""
(如果因此進入入場前塊,則可以使用)
/(BEFORE ENTRY)([^]*?)(END)/g
在\\1 , \\2, \\3
播放。 如果我能以某種方式合並捕獲組,則可以工作。
output:
的多行字符串。 arr = [{id:"1", output:">>EXAMPLE DATA<<"},...,{id:"n", output:">>Some similar Data<<"}]
編輯:對不起,我沒有看到perl
標簽。.我要刪除答案嗎? 該邏輯仍然可以重用。
如果要使用正則表達式,我將使用第二個更簡單的捕獲組。 此外,我通過一系列鍵使該解決方案通用。
請注意,使用replace
函數,除了能夠控制僅在第一個匹配項中插入結果外,還禁用了可能出現在結果中的特殊替換,例如$$
。
您不必將結果存儲在數組中,可以將本地變量用於結果。
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>
使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.