Skip to main content
 首页 » 编程设计

Python 正则表达式匹配直到多行字符

2025年05月04日22qq号

<分区>

我有一个格式如下的文件:

hello = { 
 
     a = "2354a" 
     b = "06567567h" 
 
 
} 
 
goodbye = { 
     there = "/home/afhge" 
 
} 
 
... 
 
anotherset = { 
      dsfsdf = grhbrwecs 
      dfgtmyj = 12345 
 
} 

我在 python 中使用正则表达式,我想要匹配的是大括号内的所有内容,因此生成的匹配输出将是以下列表:

['\n\n\ta = "2345a"\n\tb = "06567567h"\n\n\n', '\n\there = "/home/afhge"\n\n', '\n\tdsfsdf = grhbrwecs\n\tdfgtmyj = 12345\n\n'] 

我试过正则表达式:

desired_output = re.findall("{[^}]", file_text) 

然而这个正则表达式在列表中产生:

['{\n', '{\n', '{\n', '{\n', '{\n'] 

看起来 [^}] 匹配任何字符直到换行符。我试过这样做:

desired_output = re.findall("{[^}]", file_text, re.S) 

和

desired_output  = re.findall("{[^}]", file_text, re.M) 

没有成功:(。

谢谢!