[英]Perl RegEx - Find and Replace Repeated String
我想在以下條件下在CSV文件中查找和替換日期:
1)第一列為空白,如“”,“”,
1a)由於前兩列中的文本,$ case [1]不匹配
2)接下來的6列中的每一列都可能包含日期,如下面的$ case [0]
2a)$ case [2]不匹配,因為所有6列都是空白的
my @case = (
'"","","","1/2/2012","","","","",="12345678"',
'"Add","New","1/1/2012","1/2/2012","","","",""="0987654"',
'"","","","","","","","",="91234567"'
);
我使用了以下代碼,但它錯誤地匹配$ case [2]並影響腳本的效率:
my $argFind = (qr/^"","",("[\d\/]*",){6}(.*)/);
$replace = '"","","","","","","","",';
if (grep(/$argFind/,@case))
{
s/$argFind/$replace$2/ for @case;
#write file
}
最終結果應該是:
$case = [
'"","","","","","","","",="12345678"',
'"Add","New","1/1/2012","1/2/2012","","","",""="0987654"',
'"","","","","","","","",="91234567"'
];
我相信您應該使用Text::CSV
從CSV記錄中檢索數據值列表。 然后,您可以單獨檢查字段以檢查它們是否符合您的要求。
但只要數據自動生成並保持良好狀態,您就可以嘗試
qr[ ^ (?: "", ){2} (?: " (?: \d\d?/\d\d?/\d\d\d\d )? ", ){6} ]x;
whcih找到兩個空字段,后跟六個字段,這些字段為空或包含看起來像日期的內容。 該計划表明
use strict;
use warnings;
my @case = (
'"","","","1/2/2012","","","","",="12345678"',
'"Add","New","1/1/2012","1/2/2012","","","",""="0987654"',
'"","","","","","","","",="91234567"'
);
my $argFind = qr[ ^ (?: "", ){2} (?: " (?: \d\d?/\d\d?/\d\d\d\d )? ", ){6} ]x;
my $replace = '"",' x 8;
for (@case) {
print "$_\n" if s/$argFind/$replace/;
}
OUTPUT
"","","","","","","","",="12345678"
"","","","","","","","",="91234567"
好吧,我得到了你的最終結果:
qr/^(?:"",){3}"\d\d?\/\d\d?\/\d{4}",(?:"",){4}/;
感謝您的所有投入。 我打算用這樣的東西作為解決方案:
use warnings;
use Data::Dumper;
my @case = (
'"","","","1/2/2012","","","","",="12345678"',
'"","","1/1/11","","","","","",="12345678"',
'"","","","1/2/13","","4/3/2010","","",="987654"',
'"","","","","","","","1/3/2012",="567890"',
'"Add","New","1/1/2012","1/2/2012","","","","",="0987654"',
'"","","","","","","","",="91234567"'
);
my $argFind = (qr/^"","",("[\d\/]*",){6}/);
my $replace = '"",' x 8;
for (@case) {
unless (m/$replace/) {
s/$argFind/$replace/;
# Set flag to write file after loop
}
}
warn Dumper \@case;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.