Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace all backslashes except those starting a Unicode escape sequence?

I am trying to remove the backslashes in my dataset \; however, a simple string.replace() method will remove even the escape unicode strings and I don’t want that. I tried using re.sub("\\[^u]", " ", "\Not wanted backslashes\ unicode: \u2019\u2026"), but that also replaces the first character of the word.

Is there any way to only replace the backslash?

Thanks in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Easy. Use negative lookahead:

\\(?!u)

This pattern will match any backslash NOT followed by a u. But you can do even better, with a negative lookahead for a Unicode escape pattern:

\\(?!u[0-9A-Fa-f]{4})

This pattern will match any backslash NOT followed by a u + four hexadecimal digits.

To learn more: Positive & Negative Lookahead with Examples – Regex Tutorial

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading