Skip to main content
 首页 » 编程设计

python之正则表达式到python中配置文件中的grep字符串

2024年09月07日31artech

我有配置文件,其中包含如下所示的网络配置。

LISTEN=192.168.180.1 #the network which listen the traffic  
NETMASK=255.255.0.0 
DOMAIN =test.com 

需要从配置中获取值。以下是我当前的代码。

import re 
with open('config.txt') as f: 
      data = f.read() 
      listen =  re.findall('LISTEN=(.*)',data) 
      print listen 

变量listen包含

192.168.180.1 #the network which listen the traffic

但我不需要注释信息,但有时注释可能不像其他“NETMASK”那样存在

请您参考如下方法:

如果您真的想使用正则表达式,我建议将其更改为 LISTEN=([^#$]+)

它应该与打开评论的井号或换行符之前的任何内容匹配。