-1

I am trying to make a very simple regex replacement. Multiple others similar to this one work, but not this one.

I want every occurrence of either "/\" or "JI" character sequences to be replaced with "X". So, "/\JI" must turn into "XX".

However, here's what happens:

>>> import re
>>> phrase = '/\JI'
>>> phrase = re.sub('\/\\|JI', 'X', phrase)
>>> phrase
'/\\JI'

Why does it not detect either of the combinations and adds that second slash? regex101.com shows 2 full matches with the same string and same regex.

Andy Mac
  • 157
  • 2
  • 12
  • 2
    Use ``re.sub(r'\/\\|JI', 'X', phrase)`` – Tomás Denis Reyes Sánchez May 18 '20 at 21:31
  • For detailed info https://stackoverflow.com/questions/10585349/python-how-to-replace-backslash-with-re-sub – Gunesh Shanbhag May 18 '20 at 21:33
  • 1
    You should be using [raw strings](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals) to make sure your backslashes are not interpreted as escape characters. – 0x5453 May 18 '20 at 21:34
  • 2
    Does this answer your question? [Python how to replace backslash with re.sub()](https://stackoverflow.com/questions/10585349/python-how-to-replace-backslash-with-re-sub) – Gunesh Shanbhag May 18 '20 at 21:34
  • @GuneshShanbhag not really. That's a different question. I know how escaping and double escaping work. Still, thank you for your effort. – Andy Mac May 18 '20 at 21:43

1 Answers1

1

Use re.sub(r'/\\|JI', 'X', phrase). Note the r before the string indicating raw.