Skip to main content
 首页 » 编程设计

python之匹配字符串中的 [ ^'] but also\' 的正则表达式

2024年10月24日33mengfanrong

我正在解析一个 .SQL 文件并尝试将其写入 Mongodb。

我用了这个正则表达式,

\((\d+),'([^']+)'(?:,(\d+))(?:,(\d+))(?:,(\d+))\) 

,它适用于大多数情况。

(431532,'Fluorescent_cheese_dyes',0,0,0),(431533,'Christian_Rock_albums',0,0,0), 
(431534,'Variety_radio_stations',0,0,0),(431535,'Dean\'s_list',0,0,0), 

但是对于最后一个关于哪里有\'的情况,它没有,因为我使用了'([^']+)'来匹配字符串。当我将 '([^']+)' 更改为 '((?:(?:\')|[^'])+)' 时,它将在一个实例中匹配所有案例而不是 4 个。组将是这样的:

1.  431532 
2.  Fluorescent_cheese_dyes',0,0,0),(431533,'Christian_Rock_albums',0,0,0),(431534,'Variety_radio_stations',0,0,0),(431535,'Dean\'s_list 
3.  0 
4.  0 
5.  0 

如果第二组将字符串与 \' 匹配,我该如何处理?

请您参考如下方法:

只需使用非贪婪的. (.+?)

\((\d+),'(.+?)'(?:,(\d+))(?:,(\d+))(?:,(\d+))\) 

示例:https://regex101.com/r/zV0lZ1/1