user3837980 user3837980 - 1 month ago 8
Python Question

How do I match an exact string with special characters in it?

import re
data = "sda 8:0 0 107374182400 0 disk \r\n\root@awx1:~[root@awx ~]# s"
re.sub(r"root@qa-dc1:~\[root@qa-dc1 ~\]# s","",data)
'sda 8:0 0 107374182400 0 disk \r\n\root@qa-dc1:~[root@qa-dc1 ~]# s'


It does not gets replaced. How can I match the substring with regex and replace it?

wim wim
Answer

This is what re.escape is for.

>>> data = "sda      8:0    0 107374182400  0 disk \r\nroot@awx1:~[root@awx ~]# s"
>>> substring = re.escape(                            "root@awx1:~[root@awx ~]# s")
>>> re.sub(substring, '', data)
'sda      8:0    0 107374182400  0 disk \r\n'

Note: I removed an extra \ character from your example that I don't think was really there. Between the \r\n and the root.

Comments