我想構建一個正則表達式來搜索和替換文件。以下是腳本。正則表達式的搜索和編輯構造
#!use/bin/perl
use strict;
use warnings;
my $line = $ARGV[0];
my $find = "[^a-zA-Z0-9]+seqfile[^a-zA-Z0-9]+=[^a-zA-Z0-9]+[a-z]+..";
my $replace = "done"; open (FILE, ">>/home/user/Desktop/test") || die "cant open file \n";
my @body = <FILE>;
foreach $line (@body) {
if (my $line =~ s/$find/$replace/g){
print FILE $line;
}
else {
print "did not replace \n\n";
}
}
close(FILE);
print "reached here\n";
exit;
我正在運行的測試我的程序的示例測試文件由幾行文本組成。我想要替換的字符串存在於第一行「tobereplaced = file.aa」。我不得不使用carot(^)表示字母/數字以外的字符,因爲在我的系統中不接受空格「\ s」的正則表達式。我知道程序執行是因爲它打印出'到達此處'。任何人都可以提出
- 爲什麼使用我 指定正則表達式我的程序無法 搜索字符串。
- 爲什麼我的系統無法識別 「\ s」和給錯誤「無法識別的 逃避\ S通過在 測試通過」
- 並且還,任何人都可以提出對學習正則表達式的一些 良好來源。
感謝
查看http://stackoverflow.com/questions/934733/perl-loop-through-a-file-and-substitute/934756#934756如果你只是想要一個oneliner – 2009-06-02 15:22:49
另一種說法是「[^ a-zA -Z0-9]「是」\ P {IsAlnum}「 – Axeman 2009-06-02 18:07:14