Regular expression for parsing numbers in python
<p>Could anyone help me with the following scenario? </p>

<p>NFL season is approaching and I am working on a python script to scrape spreads off a website for analysis.  </p>

<p>scenario one: spread comes in the form -3+3</p>

<p>scenario two: spread comes in the form -3.5+3.5</p>

<pre><code>import re 

s1 = '-3+3'
s2 = '-3.5+3.5'

search1 = re.search(r'(.\d)(.*)',s1)
search2 = re.search(r'(.\d)(.*)',s2)

print search1.group(1),','search1.group(2)
print search2.group(1),',',search2.group(2)

&gt;-3 , +3
&gt;-3 , .5+3.5
</code></pre>

<p>As you can see the output of the second scenario chops off anything after the decimal place and places it in front of the next number. Can anyone help me find a solution that would be applicable to both situations? </p>

<p>Thanks!</p>

<p>As I said in the comments, this regular expression will grab any pairs of numbers, optionally preceded by +/-, with a decimal or not. </p>

<pre><code>([-+]?\d+(?:\.\d+)?)([-+]?\d+(?:\.\d+)?)
</code></pre>

<p>Also, if you are going to be using the same regular expression more than once (and especially if you will be using it dozens or more times), you should compile it before use:</p>

<pre><code>import re
pattern = re.compile(r'([-+]?\d+(?:\.\d+)?)([-+]?\d+(?:\.\d+)?)')
s1 = '-3+3'
s2 = '-3.5+3.5'
search1 = pattern.search(s1)
search2 = pattern.search(s2)
print search1.group(1), "," , search1.group(2)
</code></pre>

<p>This will increase performance potentially dozens of times over matching a raw string pattern.</p>

python regex