How to use regex to disallow non-digts but allow a dot in Python?
<p>I am new to regex and trying to remove all <strong>non-digts</strong> but keep the <strong>dot</strong> (<strong>.</strong>) of a string:</p>

<pre><code>x = ['ABCD, EFGH ', ' 20.9&amp;dog; ', ' IJKLM /&gt;']
</code></pre>

<p>So far I have tried the following:</p>

<pre><code>&gt;&gt;&gt; x = re.sub("\D", "", x)
209
</code></pre>

<p>However I am trying to get the following outcome:</p>

<pre><code>20.9
</code></pre>

<p>Thanks.</p>

<p>Instead of using the class <code>\D</code> you can define your own class of characters using <code>[...]</code>, and invert that class using <code>[^...]</code>. Now just put all the digits <code>0-9</code> and the <code>.</code> into that class:</p>

<pre><code>&gt;&gt;&gt; x = ['ABCD, EFGH ', ' 20.9&amp;dog; ', ' IJKLM /&gt;']
&gt;&gt;&gt; [re.sub("[^0-9.]", "", y) for y in x]
['', '20.9', '']
</code></pre>

<p>Of course, instead of <em>removing</em> everything that is <em>not</em> a number or dot, you could also use <code>re.findall</code> or <code>re.search</code> to get those parts of the string that <em>are</em> numbers or dot. This has the benefit that if the string contains more than one number, those will not clump together:</p>

<pre><code>&gt;&gt;&gt; z = "foo20.9bar42.1blub"
&gt;&gt;&gt; re.sub("[^0-9.]", "", z)
'20.942.1'
&gt;&gt;&gt; re.findall("[0-9.]+", z)
['20.9', '42.1']
</code></pre>

python regex python-2.7