Python正则/SQL库实现多源字段与目标字段匹配提取需求
[更新:] 已采纳答案表明无法通过Python re库一步实现,若有其他方法欢迎留言。
问题描述
我正在逆向一个大型ETL管道,希望从存储过程和视图中提取完整的数据血缘。在编写正则表达式时遇到了困难,相关代码如下:
import re select_clause = "`data_staging`.`CONVERT_BOGGLE_DATE`(`landing_boggle_replica`.`CUST`.`u_birth_date`) AS `birth_date`,`data_staging`.`CONVERT_BOGGLE_DATE`(`landing_boggle_replica`.`CUST`.`u_death_date`) AS `death_date`,(case when (isnull(`data_staging`.`CONVERT_BOGGLE_DATE`(`landing_boggle_replica`.`CUST`.`u_death_date`)) and (`landing_boggle_replica`.`CUST`.`u_cust_type` <> 'E')) then timestampdiff(YEAR,`data_staging`.`CONVERT_BOGGLE_DATE`(`landing_boggle_replica`.`CUST`.`u_birth_date`),curdate()) else NULL end) AS `age_in_years`,nullif(`landing_boggle_replica`.`CUST`.`u_occupationCode`,'') AS `occupation_code`,nullif(`landing_boggle_replica`.`CUST`.`u_industryCode`,'') AS `industry_code`,((`landing_boggle_replica`.`CUST`.`u_intebank` = 'Y') or (`sso`.`u_mySecondaryCust` is not null)) AS `online_web_enabled`,(`landing_boggle_replica`.`CUST`.`u_telebank` = 'Y') AS `online_phone_enabled`,(`landing_boggle_replica`.`CUST`.`u_hasProBank` = 1) AS `has_pro_bank`" # 该模式可捕获所有源字段,但无法捕获目标字段 okay_pattern = r"(?i)((`[a-z0-9_]+`\.`[a-z0-9_]+`)[ ,\)=<>]).*?" # 该模式可捕获目标字段,但仅能捕获第一个源字段 wrong_pattern = r"(?i)((((`[a-z0-9_]+`\.`[a-z0-9_]+`)[ ,\)=<>]).*?AS (`[a-z0-9_]+)`).*?)" re.findall(okay_pattern, select_clause) re.findall(wrong_pattern, select_clause)
核心需求
希望从如下格式的字符串中:
"...aaa....bbb...XXX....eee...fff...[多个]...ooo... YYY...ppp...ZZZ...."
捕获得到分组结果:
[aaa, bbb, XXX],
[eee, fff, ..., ooo, YYY],
[ppp, ZZZ]
其中a,b,e,f等匹配一种模式,X,Y,Z匹配另一种模式,第一种模式最多可出现约20次,之后跟随唯一的第二种模式。
补充说明
也接受使用sqlglot、sql-metadata或sqlparse库的解决方案,只是正则的文档更完善。(或许不该追求极简写法,应该分步处理,先将字符串拆分为单独的表达式。)
内容的提问来源于stack exchange,提问作者Lorinc Nyitrai
相关产品推荐
相关产品推荐

