代码之家  ›  专栏  ›  技术社区  ›  PersianGulf

将Evey Single/Double Qoutes替换为“或”

  •  0
  • PersianGulf  · 技术社区  · 5 年前

    我有6000张唱片,我想看看 INSERT 它们指向新表。它们包含单引号和双引号,mysql不能接受我的查询,因为当阻止 ' (单引号)它已关闭并生成语法错误:

    sql = "INSERT INTO tr_en_ahmadali(id,sura,aya,aya_text) VALUES({0},{1},{2},'{3}');".format(str(index), str(j[index - 1]) ,str(aya_), str(k[single_aya - 1]))
    print(sql)
    

    当我打印查询时,得到以下SQL查询:

    INSERT INTO tr_en_ahmadali(id,sura,aya,aya_text) VALUES(34,2,27,'Who, having sealed it, break God's covenant, dividing what He ordained cohered; and those who spread discord in the land will suffer assuredly.');
    

    我的问题是: 如何用python替换每个单引号和双引号?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Jan    5 年前

    您可以使用一个带有否定lookbehind的简单regex:

    (?<!\\)(["'])
    

    这需要用

    \\\1
    

    a demo on regex101.com 是的。


    整件事 Python 以下内容:
    import re
    
    string = """This ain't funny, you know.
    But this escaped one (\") won't change."""
    
    rx = re.compile(r'''(?<!\\)(["'])''')
    
    string = rx.sub(r'\\\1', string)
    print(string)
    

    another demo on ideone.com 是的。