Python: read regexps from JSON
<p>I have a JSON file where I store a mapping, which contains regexes, like the ones below:</p>

<pre><code>"F(\\d)": "field-\\\\1",
"FLR[ ]*(\\w)": "floor-\\\\1",
</code></pre>

<p>To comply with the standard I escape the backslashes, the actually regexps should contain <code>\d</code>, <code>\w</code>, and <code>\\1</code>.</p>

<p>Once I read this JSON with json.load() I still need to post-process the resulting dictionary to get correct regexps. I need to substitute a <code>\\</code> with <code>\</code>. What's the best way to this?</p>

<p>So far I tried both <code>re.sub()</code> and <code>str.replace()</code> and in both cases it's not clear how to represent a single backslash in substation.</p>

<p>For example, I don't understand why the following doesn't produce a single backslash:</p>

<pre><code>In [76]: "\\\\d".replace("\\\\", "\\")
Out[76]: '\\d'
</code></pre>

<p>It does produce a single backslash - that backslash is escaped when displayed. This is done so that characters without a non-escaped way to display them can still be unambiguously printed - otherwise, you wouldn't know whether a backslash was meant to be escaping the following character or not.</p>

<p>This can be demonstrated by checking the individual characters:</p>

<pre><code># In a terminal/REPL:
&gt;&gt;&gt;&gt; "\\\\d".replace("\\\\", "\\")[0]
'\\'
&gt;&gt;&gt;&gt; "\\\\d".replace("\\\\", "\\")[1]
'd'
&gt;&gt;&gt;&gt; "\\\\d".replace("\\\\", "\\")[2]
'd'
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
IndexError: string index out of range
</code></pre>

<p>One tip for doing regexes in python: Use raw strings. If you put an <code>r</code> before the first quote of a string literal, backslashes won't escape anything (except for an ending quote). <code>r"\n"</code> is a string containing two characters, a <code>\</code> and an <code>n</code>, equivalent to <code>"\\n"</code>. When working with regexes and other things where you need to send escape sequences, they're very helpful. See also: <a href="http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l">What exactly do âuâ and ârâ string flags do in Python, and what are raw string literals?</a></p>

python json regex python-2.7