Python 正则表达式匹配但没有评论
给定文件:Python 正则表达式匹配但没有评论,python,regex,Python,Regex,给定文件: 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:
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*+
仅匹配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']
看
或者,您可以使用以下正则表达式:
^[^;]*[^\s;]
看。如果将文件作为一个字符串读取,则可能希望将其与re.MULTILINE
标志一起使用,或作为(?m)^[^;]*[^\s;]
使用
详细信息
^
-字符串的开头(如果指定了re.M
标志,则为行)
[^;]*
-0+字符,而不是代码>
[^\s;]
-除空格和以外的字符代码>
见:
您可以使用re.split
:
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
"""
final_data = '\n'.join([a for a, _ in [re.split('\s+(?=;)', i) for i in filter(None, s.split('\n'))]])
输出:
1.29.7D59
SE5C620.86B.00.01
I/O Sensitive
POR - Reg. Value:0x1F
\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
"""
final_data = '\n'.join([a for a, _ in [re.split('\s+(?=;)', i) for i in filter(None, s.split('\n'))]])
1.29.7D59
SE5C620.86B.00.01
I/O Sensitive
POR - Reg. Value:0x1F