簡體   English   中英

如何在Python中轉義所有未轉義的斜杠

[英]How to escape all unescaped slashes in Python

我在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)

如果此時連續反斜杠的數量為奇數,則僅替換反斜杠。

你不需要一個正則表達式,如果你只是做一個簡單的字符串替換來加倍所有反斜杠后跟另一個字符串替換為加倍已經加倍的那些然后你得到你想去的地方:

>>> path = "C:\\Temp\\\\TestEmpty"
>>> path.replace('\\','\\\\').replace(r'\\\\', r'\\')
'C:\\\\Temp\\\\TestEmpty'

或者,首先加倍加倍,然后加倍所有反斜杠:

>>> path.replace('\\\\', '\\').replace('\\', '\\\\')
'C:\\\\Temp\\\\TestEmpty'

我使用以下組合來回避一下:

escaped_path = re.sub( r'(\\)+', '/', path).replace('/', '\\')

(它具有額外的好處,即路徑的基本衛生設施,某人(我)可能因更換反斜杠而貪婪地輸入錯誤。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM