【问题标题】:Replacing double backslash and brackets in Python在 Python 中替换双反斜杠和括号
【发布时间】:2013-03-11 09:15:12
【问题描述】:

我正在尝试编写一个脚本,可以将 \\[\\] 之类的内容转换为 $$,以便将 MultiMarkdown 文档转换为可以在 HTML 中显示方程式的 Pandoc markdown 文档。我正在使用 Python 使用

查找这些字符的所有实例
 matchstring=r'\\['
 re.sub(matchstring,'$$',content)

但是我遇到了以下错误:

unexpected end of regular expression:line 15:matchstring=re.compile(r'\\[')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 190:
return _compile(pattern, flags)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 245:
raise error, v # invalid expression

很可能是因为我在其中的最后一个[。有谁知道解决这个问题的方法吗?

【问题讨论】:

    标签: python pandoc multimarkdown


    【解决方案1】:
    pandoc -f markdown_mmd -t markdown
    

    会为你做这件事! (对于 pandoc >= 1.11)

    【讨论】:

    • 哇哦!很高兴知道。
    【解决方案2】:

    转义[

    matchstring=re.compile(r'//\[')
    

    或者更好的是,使用:

    content.replace("//[", "$$")
    

    并且根本不涉及正则表达式。

    【讨论】:

    • 如何在文档中进行多次替换?我有不同的模式要匹配。我应该为我想要匹配的所有模式做content.replace("//[", "$$")content.replace("//]", "$$"),还是有更好的方法?
    • 刚刚意识到我可以使用content.replace("//[", "$$")).replace(r"\\]", "$$") 进行多次替换迭代。谢谢@Igor!
    【解决方案3】:

    你的问题是你写的是r'//[',而不是r'\\[', 但无论如何尝试更好:

    matchstring.replace(r'\\[', '$$').replace(r'\\]', '$$')
    

    【讨论】:

    • 我的错。我混淆了正斜杠和反斜杠。在问题中修复它们
    【解决方案4】:

    如果您在正则表达式中使用“[”,我会假设它需要在正则表达式中使用时对其进行转义。

    尝试以下方法之一:

    content = "testing123//]testing456"
    matchstring = "//]"
    result = content.replace(matchstring, "$$")
    print result
    

    content = "testing123//]testing456"
    matchstring = '(//\])'
    result = re.sub(matchstring,'$$',content)
    print result
    

    两者都应该适合您的目的。

    【讨论】:

    • 刚刚看到下一条评论..如果只是要替换的“]”字符,那么试试:matchstring =“]”
    • 上面的评论是针对第一个例子的。对于第二个,使用 matchstring = '(\])'
    • 要同时处理两者("[" & "]"),尝试使用类似这样的东西:re.sub('(\]|\[)','$$' ,内容)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多