【问题标题】:Replace spaces between specific characters only using regex仅使用正则表达式替换特定字符之间的空格
【发布时间】:2022-08-19 14:38:30
【问题描述】:

我正在尝试使用正则表达式用\\\\; 替换markdown 文档中包含的乳胶中的空格。
在我使用的 md 包中,所有乳胶都包裹在 $$$

我想更改以下内容

\"dont edit this $result= \\frac{1}{4}$ dont edit this $$some result=123$$\"

对此

\"dont edit this $result=\\\\;\\frac{1}{4}$ dont edit this $$some\\\\;result=123$$\"

我已经设法使用下面的混乱函数来做到这一点,但想使用正则表达式来获得更清洁的方法。任何帮助,将不胜感激

import re
vals = r\"dont edit this $result= \\frac{1}{4}$ dont edit this $$some result=123$$\"
def cleanlatex(vals):
    vals = vals.replace(\" \", \"  \")
    char1 = r\"\\$\\$\"
    char2 = r\"\\$\"
    indices = [i.start() for i in re.finditer(char1, vals)]
    indices += [i.start() for i in re.finditer(char2, vals.replace(\"$$\",\"~~\"))]

    indices.sort()
    print(indices)
    # check that no of $ or $$ are even
    if len(indices) % 2 == 0:
        while indices:
            start = indices.pop(0)
            finish = indices.pop(0)
            vals = vals[:start] + vals[start:finish].replace(\'  \', \'\\;\') + vals[finish:]
    
    vals = vals.replace(\"  \", \" \")
    return vals

print(cleanlatex(vals))

输出:

[18, 39, 60, 78]   
dont edit this $result=\\\\;\\frac{1}{4}$ dont edit this $$some\\\\;result=123$$

    标签: python regex


    【解决方案1】:

    使用正则表达式,我仍然会分两步完成:

    • 使用正则表达式识别美元(或双美元)之间的部分
    • 在这些部分中,用简单的replace 调用替换空格
    def cleanlatex(vals):
        return re.sub(r"(\$\$?)(.*?)\1", lambda m: m[0].replace(" ", r"\;"), vals)  
    

    如果美元不匹配,这仍然会进行替换,直到没有更多一对找到匹配的美元。这是与您的代码工作方式不同的行为,在美元不匹配时不会替换任何内容。

    当美元被“嵌套”时,比如在“$$nested $ here$$”中,那么在这个解决方案中,内部的美元将不会被视为分隔符。或者,如果双美元恰好跟在单美元之后,则双美元将被解释为恰好彼此跟随的两个单美元。所以“$part one$$part two$”将标识两个部分,每个部分用一个美元分隔。

    您的问题没有给出任何这样的边界条件(其中有很多),因此解决方案可能需要一些调整。

    【讨论】:

    • 谢谢!这比预期的要好!
    【解决方案2】:

    我从没想过lambda!谢谢 @trincot您的回答涵盖了我什至不知道使用正则表达式可能实现的事情。我正在尝试破译这种模式,如果可以的话,我希望得到一些澄清?我真的很感激它 我看过 re docs 但仍然对以下内容感到困惑

    1. 是否有理由使用 ($$?) 而不是 ($+)?
    2. \1 -> 这只是保持模式整洁的一种方法,如果我使用 \2 它将复制第二个捕获组?
    3. 吗? in (.*?) 让它找到匹配模式的最短字符串?
    4. 为什么 m[0] 即为什么索引在 0

      再次感谢你的回复

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      相关资源
      最近更新 更多