Skip to main content
 首页 » 编程设计

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

2025年05月04日28mfryf

我正在尝试在 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