解析sfvformat文件的正则表达式

2024-06-16 09:48:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python编写一个regex来解析sfv文件。 基本上,这些行的格式是

filename crc_bytes

但是可以到处添加空白,包括文件名。所以真正的形式是

(whitespaces)filename(whitespaces)crc_bytes(whitespaces)

当文件名可以包含空格时。在

现在,我试图提取文件名和crc_字节。所以我试过:

'\s*(.+)\s+([^\s]+)'

但它解析了

^{pr2}$

作为

'filename with spaces   ', 'crc' 

//空格太多---------^

你知道怎么去掉这些空间吗?也许,不知怎么的,回头看看?在

额外问题:

sfv文件中的注释是以“;”开头的行。如果有人能在regex上处理评论,我将永远欠他的债。在

谢谢!!在


Tags: 文件字节bytes文件名格式filename空白形式
1条回答
网友
1楼 · 发布于 2024-06-16 09:48:47

使用空格处理文件名

使用(.+\S)强制文件名以非空白('\S)字符结尾。在

>>> import re
>>> reg=re.compile('\s*(.+\S)\s+(\S+)')
>>> reg.findall(line)
[('filename with spaces', 'crc')]

避免评论

您可以使用lookahead或向regex添加否定检查。不过,我认为添加另一个regex会更具可读性:

^{pr2}$

现在我们有三行,其中两行是评论行。以下仅分析不是注释的行:

>>> [reg.findall(l) for l in lines if not comment_line_regex.match(l)]
[[('filename with spaces', 'crc')]]

或者,用更详细的方式:

>>> for line in lines:
...     if not comment_line_regex.match(line):
...             print reg.findall(line)
... 
[('filename with spaces', 'crc')]

相关问题 更多 >