Regex: How to replace with the string literal “\1”?
-
28-09-2020 - |
Question
I have a string, say r"a"
. I want to replace every r"a"
with the string r"\1"
, but my regex engine does not understand this.
I have tried:
r"\1"
-- crashes (can't match group 1 because there is no group 1)r"\\1"
-- crashes (not sure why)
Is this a limitation of my (proprietary) regex engine, or is it a general problem? Is there an elegant way of solving it? (I could e.g. replace "a" by "/1" and then StrReplace( "/", r"\" )... but that's not nice!)
Solution
The correct way would be to use r"\\1"
as a replace string. So if your proprietary regex engine/language chokes on a \\
, you should fix this bug.
If you look at your example, you don't need a regex engine at all. But perhaps the example is simpler than the actual requirement...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow