2016-01-23 48 views
2

我討厭這樣做,但我只是試圖找出正則表達式,我已經ban了幾個小時,所以我終於訴諸專家。援助建設正則表達式

-1,AAABO,ABOAO 
-2,ABBBO,BABBO 
-3,AAACO,ACAAO 
-4,ABDDO,BADDO 
-5,AAABF,ABFAA 
-6,BBBGO,BGBBO 

我期待匹配多個子字符串,但只有逗號之間。

例如:

AA and B would return rows 1,5 
BB and O would return 2 and 6 
BBB and G would return row 6 
AA C and O would return row 3 

需要我會動態地建立這個。

的第二步驟將在所述串的開頭或結尾的第二逗號

例如後過濾(啓動):

AB would return row 1 and 5 

例如(結束):

BO would return row 2 and 6 

然後我需要結合所有3個過濾器。

例如

AAA O (contains from 2nd column) 
AB (begins with) 
O  (ends with) 

返回行1

如果需要,我可以做多遍。

我會很高興與任何指導。

+1

你使用什麼工具? – e0k

+0

@ e0k我將使用PERL –

+0

爲什麼'AA'和'B'返回第2行?另外,「AA C和O」是指「AA」還是「C」和「O」? – 2016-01-23 00:58:51

回答

3

你想要的正則表達式

/^.*?,(?=[^,]*AAA)(?=[^,]*O).*?,AB.*O$/ 

與評論

/ 
    ^.*?,   # consume the first field 
    (?=[^,]*AAA) # look ahead in the 2nd field for AAA 
    (?=[^,]*O)  # look ahead in the 2nd field for O 
    .*?,   # consume the 2nd field 
    AB.*O$   # the 3rd field starts with AB and ends with O 
/x 

它可以產生這樣的

sub gen_regex { 
    my ($begins, $ends, @contains) = @_; 
    my $regex = "^.*?," 
       . join("", map {"(?=[^,]*$_)"} @contains) 
       . ".*?,$begins.*$ends\$"; 
    return qr/$regex/; 
} 

my $re = gen_regex('AB', 'O', qw(AAA O)); 

,然後用它是這樣的:

while (<>) { say $. if /$re/ } 
+0

有一些調整,它出色地工作。一旦你看到它,它幾乎看起來很容易。但我知道更好!謝謝! –