gpt4 book ai didi

python - 如何转义Python中所有未转义的斜杠

转载 作者:行者123 更新时间:2023-11-30 23:37:57 25 4
gpt4 key购买 nike

我在Python中有一个部分转义的路径,如下所示:

path = "C:\\Temp\\\\TestEmpty" # Actual value = C:\Temp\\TestEmpty

我想让所有斜杠都像这样加倍:

escapedpath = "C:\\\\Temp\\\\TestEmpty" # Actual value = C:\\Temp\\TestEmpty

我从一些正则表达式开始

escapedpath = re.sub("[a-zA-Z0-9 _:-](\\)[a-zA-Z0-9 _:-]", "\\\\", path)

...但是这当然会删除 \\s

之前和之后的字符

这是怎么做到的?

最佳答案

result = re.sub(r"""(?x)
(?<!\\) # Make sure that there is no backslash before the current position
\\ # Match a backslash
(?= # only if...
(?:\\\\)* # an even number of backslashes follows (including zero)
(?!\\) # and no further backslashes follow after that
) # (End of lookahead assertion)""",
r"\\\\", subject)

仅当此时连续反斜杠的数量为奇数时才替换反斜杠。

关于python - 如何转义Python中所有未转义的斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14977410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com