Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式匹配但没有评论_Python_Regex - Fatal编程技术网

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