用于搜索额外反斜杠的正则表达式

2024-06-16 09:50:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含文件位置和地址的文本文件(例如%Software\Policies\Microsoft\Windows\Safer\CodeIdentifiers\0\Hashes

然而,对于其中一些我有多个反斜杠在一行,我想摆脱他们,并取代他们只有一个反斜杠。。是否有一个正则表达式可以用来标识所有额外的反斜杠(一行中不止一个)


Tags: 文件windows地址software标识microsoft文本文件斜杠
2条回答

您有机会查看python文档吗? 你需要知道:

'*' Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.

'?' Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’.

'\' Either escapes special characters (permitting you to match characters like '*', '?', and so forth), or signals a special sequence. so to check '\' you need to put it as '\'. For example, to match a literal backslash, one might have to write '\\' as the pattern string, because the regular expression must be \, and each backslash must be expressed as \ inside a regular Python string literal.

如果您需要知道如何在python中使用regex: Python string.replace regular expression

试试这个:

\\{2,}

替换为:

\\

Demo

示例代码:

import re
regex = r"\\{2,}"
test_str = r"%Software\\Policies\\\\Microsoft\\Windows\\Safer\\CodeIdentifiers\\0\\Hashes\\"


subst = r"\\"
result = re.sub(regex, subst, test_str, 0)

if result:
    print (result)

Run it

相关问题 更多 >