问题描述
我不是 Python 开发人员,但我正在使用 Python 脚本来将 SQLite 转换为 MySQL
I'm not a Python developer, but I'm using a Python script to convert SQLite to MySQL
建议的剧本很接近,但没有雪茄,正如他们所说.
The suggested script gets close, but no cigar, as they say.
给我一个问题的那一行是:
The line giving me a problem is:
line = re.sub(r"([^'])'t'(.)", r"\1THIS_IS_TRUE\2", line)
...当然还有等价的 false ('f') 行.
...along with the equivalent line for false ('f'), of course.
我看到的问题是,只有在任何给定行中第一次出现的 't' 会被替换.
The problem I'm seeing is that only the first occurrence of 't' in any given line is replaced.
所以,输入到脚本中,
INSERT INTO "cars" VALUES(56,'Bugatti Veyron','BUG 1',32,'t','t','2011-12-14 18:39:16.556916','2011-12-15 11:25:03.675058','81');
...给...
INSERT INTO "cars" VALUES(56,'Bugatti Veyron','BUG 1',32,THIS_IS_TRUE,'t','2011-12-14 18:39:16.556916','2011-12-15 11:25:03.675058','81');
我提到我不是 Python 开发人员,但我已尝试自己解决此问题.根据文档,我知道 re.sub 应该替换所有出现的 't'.
I mentioned I'm not a Python developer, but I have tried to fix this myself. According to the documentation, I understand that re.sub should replace all occurrences of 't'.
我很想知道为什么我只看到替换了第一个出现,谢谢.
I'd appreciate a hint as to why I'm only seeing the first occurrence replaced, thanks.
推荐答案
您在示例中想要的两个替换重叠 - 't'
的两个实例之间的逗号将被匹配(.)
在第一种情况下,所以 ([^'])
在第二种情况下永远没有机会匹配它.这个稍微修改的版本可能会有所帮助:
The two substitutions you'd want in your example overlap - the comma between your two instances of 't'
will be matched by (.)
in the first case, so ([^'])
in the second case never gets a chance to match it. This slightly modified version might help:
line = re.sub(r"(?<!')'t'(?=.)", r"THIS_IS_TRUE", line)
此版本使用前瞻和后视语法,在此处进行了描述.
This version uses lookahead and lookbehind syntax, described here.
这篇关于re.sub 不替换所有出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!