[英]Perl Regex: Matching From Start of File to Pattern
我有一個包含多個HTTP響應(包括HTTP標頭)的XML文件,我想將單個響應寫到文件中,而只包含內容而不是標頭。 我正在努力刪除文件開頭的HTTP標頭,而不會弄亂其余部分
#!/usr/bin/perl
use XML::Simple;
use MIME::Base64;
use URI::Escape;
#CheckArgs
....
my $input = $ARGV[0];
# Parse XML
my $xml = new XML::Simple;
my $data = $xml->XMLin("$input");
# Iterate through the file
for (my $i=0; $i < @{$data->{item}}; $i++){
my $status = $data->{item}[$1]->{status};
my $path = $data->{item}[$i]->{path};
if ($status != "200") {
print "Skipping $path due to status of $status\n";
next;
}
print "$status $path\n";
my $filename = uri_escape($path);
# The Content is Base64 Encoded
my $encoded = $data->{item}[$i]->{response}->{content};
my $decoded = decode_base64($encoded);
# Remove HTTP headers
$decoded =~ s/^(.*?)((\r\n)|\n|\r){2}//gm;
open(IMGFILE, "> $filename") or die("Can't open $filename: ".$@);
binmode IMGFILE;
print IMGFILE $decoded;
close IMGFILE;
}
在搜索和替換之前, $decoded
看起來像這樣
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 12 Nov 2025 20:79:99 GMT
Content-Type: application/pdf
Content-Length: 88151
Last-Modified: Mon, 14 Sep 2025 20:79:99 GMT
Connection: keep-alive
ETag: "123123-123546"
Expires: Thu, 19 Nov 2025 20:79:99 GMT
Cache-Control: max-age=123456
Accept-Ranges: bytes
%PDF-1.6
%âãÏÓ
54 0 obj
<<
/Linearized 1
/O 56
/H [ 720 305 ]
/L 45164
/E 7644
/N 10
/T 43966
>>
endobj
[Lots more binary and text]
因此,我嘗試從文件的開頭與以下兩行匹配兩個新行的第一個實例:
$decoded =~ s/^(.*?)((\r\n)|\n|\r){2}//m;
# s => Search Replace
# ^ => Start of file
# (.*?) => Non-greedy match anything including \r and \n
# ((\r\n)|\n|\r){2} => two new lines
# // => Replace with empty string
# m multiline to allow . to match \r\n
經過大量的正則表達式后,我無法獲得想要的結果,從上面的示例中,我希望我的新文件以字符%PDF-1.6
開頭,這些字符以及它們之后的所有內容均應保持不變。 請注意,PDF文件只是一個示例,我想使用它來處理許多其他文件類型。
$decoded =~ s/^(.*?)((\r\n)|\n|\r){2}//m;
# matches \r\n due to or. So Try
$decoded =~ s/^(.*?)((\r\n)|([^\r]\n)|(\r[^\n])){2}//m;
m多行允許。 匹配\\ r \\ n
/m
修飾符僅影響^
和$
字符。 您需要/s
允許.
匹配LF
(((\\ r \\ n)| \\ n | \\ r){2} =>兩行
有一個已經執行此操作的元字符- \\R
我建議像
$decoded =~ s/^.*?\R{2,}//s
會做你想要的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.