修改 - 鑑於你的更新後,這是一種方式,你可以做到這一點。
它通過代碼塊構造(?{})
在主正則表達式中進行拆分。
這樣做有點棘手,但它避免了做一個額外的正則表達式。
主要正則表達式構建@vals陣列和獲取目標串# target..
在每場比賽。其嚴格的線性導向。在每次比賽中,來自@vals的正則表達式構造爲
並且用於匹配目標字符串。
祝你好運!
的Perl
use strict;
use warnings;
$/ = undef;
my $data = <DATA>;
my @vals;
while ($data =~/
^ # BOL
(?{ @vals =() }) # Code block - Initialize @vals
(?: # Text & vals cluster
[^\n\[]* # Text - not newline nor '['
\[ # '[' opening vals bracket
(?: # Vals cluster
([^\n;\]]*) # (1), Optional value
;? # Optional ';'
(?{
# Code block - Push capture onto @vals
push (@vals, $^N)
if length $^N;
})
)* # End Vals cluster, do 0 to many times
\] # ']' closing val bracket
)* # End Text & vals cluster, do 0 to many times
[^\n#]* # Text - not newline nor '#'
\# # '#' Target string delimiter
(.*) # (2), Optional Target string
$ # EOL
/xmg)
{
my $target = $2;
print "----------\n$target\n";
if (@vals) {
my $rx = '(' . join('|', map { quotemeta } @vals) . ')';
my $matched = 0;
while ($target =~ /$rx/g) {
print "$1,"; $matched = 1;
}
print "\n" if $matched;
}
}
__DATA__
Hello, Chester [McAllister;Scientist] lives in Boston [Massachusetts;USA;Fenway Park] # McAllister works in USA
I'm now working in New-York [NYC;USA] # I work in USA
Nothing [here;;;
Nothing [there;;story;] [;] # End of here story
# More junk here
輸出
McAllister works in USA
McAllister,USA,
----------
I work in USA
USA,
----------
End of here story
story,
----------
More junk here
來源
2014-11-21 16:47:09
sln
你的意思是這個'\ [[^; \ n] *(?:; [^; \ n] *)+ \]'http://regex101.com/r/uT5cC0/2' – 2014-11-21 16:23:22
你是什麼試圖做到,讓他們成爲一個數組? – sln 2014-11-21 16:29:33
@AvinashRaj我試過這個'if($ sentence =〜/(\ [[^;] *(?:; [^; * *)+ \])/ g)print $ 1。「\ n」 個; 「但第一行的結果是:'[McAllister;科學家]住在波士頓[馬薩諸塞州;美國;芬威公園]' – 2014-11-21 16:44:34