Re.sub Not Replacing All Occurrences
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: li
Solution 1:
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.
Solution 2:
How about
line = line.replace("'t'", "THIS_IS_TRUE").replace("'f'", "THIS_IS_FALSE")
without using re
. This replaces all occurrences of 't'
and 'f'
. Just make sure that no car is named t
.
Solution 3:
The first match you see is ,'t',
. Python proceeds starting with the next character, which is '
(before the second t
), subsequently, it cannot match the ([^'])
part and skips the second 't'
.
In other words, subsequent matches to be replaced cannot overlap.
Solution 4:
using re.sub(r"\bt\b","THIS_IS_TRUE",line)
:
In [21]: strs="""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');"""
In [22]: print re.sub(r"\bt\b","THIS_IS_TRUE",strs)
INSERT INTO "cars" VALUES(56,'Bugatti Veyron','BUG 1',32,'THIS_IS_TRUE','THIS_IS_TRUE','2011-12-14 18:39:16.556916','2011-12-15 11:25:03.675058','81');
Post a Comment for "Re.sub Not Replacing All Occurrences"