-1

I have a text file which contains files locations and addresses (e.g. %Software\Policies\Microsoft\Windows\Safer\CodeIdentifiers\0\Hashes)

However for some of them I have multiple backslashes in a row which I want to get rid off and replace them by only one backslashes .. is there a regular expression that I can use to identify all extra backslashes (more than one in a row) ?

Sebastian Proske
  • 8,255
  • 2
  • 28
  • 37
analeen
  • 19
  • 2

2 Answers2

0

Try this:

\\{2,}

Replace By:

\\

Demo

Sample Code:

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

Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
0

Did you got the chance to look into the python documentation? Regex: you'll need to know:

'*' 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.

If you need to know how to use regex in python: Python string.replace regular expression

Community
  • 1
  • 1