gpt4 book ai didi

python正则表达式查找匹配的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:29 25 4
gpt4 key购买 nike

我正在尝试在 Python 中使用正则表达式在字符串中查找匹配的字符串。 字符串 如下所示:

band   1 # energy  -53.15719532 # occ.  2.00000000

ion s p d tot
1 0.000 0.995 0.000 0.995
2 0.000 0.000 0.000 0.000
tot 0.000 0.996 0.000 0.996

band 2 # energy -53.15719532 # occ. 2.00000000

ion s p d tot
1 0.000 0.995 0.000 0.995
2 0.000 0.000 0.000 0.000
tot 0.000 0.996 0.000 0.996

band 3 # energy -53.15719532 # occ. 2.00000000

我的目标是找到tot 之后的字符串。所以匹配的字符串将是这样的:

['0.000  0.996  0.000  0.996', 
'0.000 0.996 0.000 0.996']

这是我当前的代码:

pattern = re.compile(r'tot\s+(.*?)\n', re.DOTALL)
pattern.findall(string)

但是,输出给我:

['1  0.000  0.995  0.000  0.995',
'0.000 0.996 0.000 0.996',
'1 0.000 0.995 0.000 0.995',
'0.000 0.996 0.000 0.996']

知道我做错了什么吗?

最佳答案

您不需要 DOTALL 标志。删除它并使用 MULTILINE相反。

pattern = re.compile(r'^\s*tot(.*)', re.MULTILINE)

这匹配所有以 tot 开头的行。该行的其余部分将在第 1 组中。

引用 documentation ,强调我的:

re.DOTALL

Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.

请注意,无需正则表达式即可轻松完成此操作。

with open("input.txt", "r") as data_file:
for line in data_file:
items = filter(None, line.split(" "))
if items[0] == "tot":
# etc

关于python正则表达式查找匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39319897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com