Regular expression to replace all occurrences of U.S
<p>I'm trying to write a regular expression to replace all occurrences of U.S. . Here's what I thought would work.</p>

<pre><code>string = re.sub(r'\bU.S.\b', 'U S ', string)
</code></pre>

<p>When I run this it only finds the first occurrence. Why is this and how can I resolve this issue. Thanks </p>

<p>The problem is that <code>.</code> has special meaning in regular expressions (it matches any character), so it needs to be escaped.</p>

<pre><code>string = re.sub(r'\bU\.S\.', 'U S ', string)
</code></pre>

<p>Also, you shouldn't use <code>\b</code> after <code>.</code>. <code>\b</code> matches between a word and non-word character. Since <code>.</code> is a non-word character, it will only match if the <code>.</code> is followed by a word character, e.g. <code>U.S.foo</code>, but not <code>U.S. currency</code> because the <code>.</code> is followed by space, which isn't a word character.</p>

<p><a href="http://ideone.com/ZPtTDc" rel="nofollow">DEMO</a></p>

python