對於這樣的樣本數據:
my $temp_comment =
'CR1234: "Then some text"
CRs 2345, 3456, 45, 567
CR678 "Some Text"';
嘗試:
$temp_comment =~ s/(,)|[^\d\n]+/$1?' ':''/semg;
,或者,如果你想貼近字符串模板:
$temp_comment =~ s/^ # multi-line mode, line start
\s* # leading blanks?
CR # CR tag
\D* # non-number stuff
( # start capture group
(?:\d+ [,\s]*)+ # find (number, comma, space) groups
) # end capture group
\D* # skip remaining non-number stuff
$ # multi-line mode, line end
/$1/mxg; # set multi-line mode + regex comments "x"
但你必須刪除數字組中的逗號後續步驟。
$temp_comment =~ tr/,//d; # remove commas in the whole string
或
$temp_comment =~ s/(?<=\d),(?=\s\d)//g; # remove commas between numbers '11, 22'
對於 「足下」,你必須使用/e
修改:
$temp_comment =~ s{^ # line start
\s* # leading blanks?
CR # CR tag
\D* # non-number stuff
((?:\d+ [,\s]*)+) # single or group of numbers
\D* # non number stuff
$ # line end
}
{do{(local$_=$1)=~y/,//d;$_}}mxeg;
這意志,在上述數據,導致:
1234
2345 3456 45 567
678
但的確,請使用,如果可能的話,更簡單的兩步法。後一個正則表達式可能會成爲繼任者的維護噩夢。
這是非常不清楚。你不能給我們一些*真實的*數據和你想要的相應的輸出嗎? 「X」字符應該是數字嗎? – Borodin 2012-07-23 19:11:05
Brock,其他兩行輸入的預期輸出是多少?您的正則表達式是否應該與CRXXX部分或後面的「某些文本」匹配? – 2012-07-23 19:11:58
你想要什麼輸出? – ikegami 2012-07-23 19:16:36