[英]Python Regular Expression Extract Chunk of Data From Binary File
我有一個二進制文件。 從該文件中,我需要使用python正則表達式提取少量數據。
我需要提取在空字符集之間存在的非空字符集。
例如,這是主要字符集:
\\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ XFF \\ XFE \\ XFE \\ X00 \\ X00 \\ X23 \\ X41 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X41 \\ X49 \\ X57 \\ X00 \\ X00 \\ X00 \\ X00 \\ X32 \\ X41 \\ X49 \\ X57 \\ X00 \\ X00 \\ X00 \\ X00 \\ X32 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X00 \\ X56 \\ X65 \\ X00 \\ X35 \\ X56
正則表達式應從上述主集中提取以下字符集:
\\ xff \\ xfe \\ xfe \\ x00 \\ x00 \\ x23 \\ x41,\\ x41 \\ x49 \\ x57 \\ x00 \\ x00 \\ x00 \\ x00 \\ x32 \\ x41 \\ x49 \\ x57 \\ x00 \\ x00 \\ x00 \\ x00 \\ x00 \\ x32和\\ x56 \\ X65 \\ X00 \\ X35 \\ X56
重要的是,如果連續獲得5個以上的空字節,則僅應將這些空字符設置為分隔符。否則,應將此空字節包括在非空字符中。 在給定的示例中您可以看到,提取的字符集中也幾乎沒有空字符。
如果沒有任何意義,請告訴我,我將嘗試以更好的方式進行解釋。
提前致謝,
您可以將split和lstrip用於列表推導,如下所示:
s='\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xfe\xfe\x00\x00\x23\x41\x00\x00\x00\x00\x00\x00\x00\x00\x41\x49\x57\x00\x00\x00\x00\x32\x41\x49\x57\x00\x00\x00\x00\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x56\x65\x00\x35\x56'
sp=s.split('\x00\x00\x00\x00\x00')
print [i.lstrip('\x00\\') for i in sp if i != ""]
輸出:
['\xff\xfe\xfe\x00\x00#A', 'AIW\x00\x00\x00\x002AIW\x00\x00\x00\x002', 'Ve\x005V']
您可以分割為\\x00{5,}
這是5個或更多的零。 它是您指定的分度。
在Perl中,它是這樣的
Perl測試用例
$strLangs = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xfe\xfe\x00\x00\x23\x41\x00\x00\x00\x00\x00\x00\x00\x00\x41\x49\x57\x00\x00\x00\x00\x32\x41\x49\x57\x00\x00\x00\x00\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x56\x65\x00\x35\x56";
# Remove leading zero's (5 or more)
$strLangs =~ s/^\x00{5,}//;
# Split on 5 or more 0's
@Alllangs = split /\x00{5,}/, $strLangs;
# Print each language characters
foreach $lang (@Alllangs)
{
print "<";
for ( split //, $lang ) {
printf( "%x,", ord($_));
}
print ">\n";
}
輸出>>
<ff,fe,fe,0,0,23,41,>
<41,49,57,0,0,0,0,32,41,49,57,0,0,0,0,32,>
<56,65,0,35,56,>
這是在Python中進行操作的方法。 我必須關閉str.strip()
並在前導和尾隨null處獲取正則表達式模式,以防止在re.split()
返回的結果列表的開頭包含額外的空字符串。
import re
data = ('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xfe\xfe\x00\x00\x23\x41'
'\x00\x00\x00\x00\x00\x00\x00\x00\x41\x49\x57\x00\x00\x00\x00\x32\x41'
'\x49\x57\x00\x00\x00\x00\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
'\x00\x00\x00\x00\x00\x56\x65\x00\x35\x56'
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
chunks = re.split(r'\000{6,}', data.strip('\x00'))
# display results
print ',\n'.join(''.join('\\x'+ch.encode('hex_codec') for ch in chunk)
for chunk in chunks),
輸出:
\xff\xfe\xfe\x00\x00\x23\x41,
\x41\x49\x57\x00\x00\x00\x00\x32\x41\x49\x57\x00\x00\x00\x00\x32,
\x56\x65\x00\x35\x56
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.