给定的文件:
1.29.7D59 ; This field should not be edited
SE5C620.86B.00.01 ; This field should not be edited
I/O Sensitive ;Options: Balanced=00: I/O Sensitive=02
POR - Reg. Value:0x1F ;Options: 0.0%=00: 0.1%=01
待办事项:
1.29.7D59
SE5C620.86B.00.01
I/O Sensitive
POR - Reg. Value:0x1F
因此我需要提取1.29.7D59、SE5C620.86B.00.01等。 试试是
\s*;+
但它不起作用,也许我需要继续看看。正则表达式的新手,所以不要。
请帮忙
请您参考如下方法:
\s*;+ 只匹配 0+ 个空白字符,然后匹配 1+ 个 ; 字符。如果您使用模式拆分单独的行,则获取第一项:
import re
s='''1.29.7D59 ; This field should not be edited
SE5C620.86B.00.01 ; This field should not be edited
I/O Sensitive ;Options: Balanced=00: I/O Sensitive=02
POR - Reg. Value:0x1F ;Options: 0.0%=00: 0.1%=01'''
lines = s.split('\n')
res = []
for line in lines:
res.append(re.split(r'\s*;', line)[0])
print(res)
# => ['1.29.7D59', 'SE5C620.86B.00.01', 'I/O Sensitive', 'POR - Reg. Value:0x1F']
参见 this Python demo .
或者,您可以使用以下正则表达式:
^[^;]*[^\s;]
参见 regex demo .如果您将文件作为一个字符串读取,您可能希望将其与 re.MULTILINE 标志一起使用,或者作为 (?m)^[^;]*[^\s;] 。
详情
^- 字符串的开始(如果指定了re.M标志则为行)[^;]*-;以外的 0+ 个字符[^\s;]- 除了空格和;以外的字符。
参见 Python online demo :
import re
s='''1.29.7D59 ; This field should not be edited
SE5C620.86B.00.01 ; This field should not be edited
I/O Sensitive ;Options: Balanced=00: I/O Sensitive=02
POR - Reg. Value:0x1F ;Options: 0.0%=00: 0.1%=01'''
print(re.findall(r'^[^;]*[^\s;]', s, re.M))
# => ['1.29.7D59', 'SE5C620.86B.00.01', 'I/O Sensitive', 'POR - Reg. Value:0x1F']
