Skip to content

Instantly share code, notes, and snippets.

@rudifa
Last active July 7, 2016 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rudifa/7552148 to your computer and use it in GitHub Desktop.
Save rudifa/7552148 to your computer and use it in GitHub Desktop.
define and test a regex pattern that matches valid floating point number strings
# test_floating_point_number_re_pattern.py
# Rudi Farkas 19 Nov 2013
import re
# define a regex pattern that matches valid floating point number strings
floating_point_number_re_pattern = fpn_rpat = "[-+]?\s*(?:\d+(?:\.(?:\d+)?)?|\.\d+)(?:[eE][-+]\d+)?"
if __name__ == '__main__':
import unittest
class Test_fp(unittest.TestCase):
# compile it into a regex and test it
def setUp(self):
self.re = re.compile('and the number is (?P<nbr>{0}),'.format(fpn_rpat))
def test_number_1(self):
s = 'and the number is 42, as expected'
m = self.re.search(s)
self.assertEqual(42, float(m.groupdict()['nbr']))
def test_number_2(self):
s = 'and the number is 42.3, as expected'
m = self.re.search(s)
self.assertEqual(42.3, float(m.groupdict()['nbr']))
def test_number_3(self):
s = 'and the number is -42.31, as expected'
m = self.re.search(s)
self.assertEqual(-42.31, float(m.groupdict()['nbr']))
def test_number_4(self):
s = 'and the number is +42.31, as expected'
m = self.re.search(s)
self.assertEqual(42.31, float(m.groupdict()['nbr']))
def test_number_5(self):
s = 'and the number is 6., as expected'
m = self.re.search(s)
self.assertEqual(6, float(m.groupdict()['nbr']))
def test_number_6(self):
s = 'and the number is .6, as expected'
m = self.re.search(s)
self.assertEqual(0.6, float(m.groupdict()['nbr']))
def test_number_7(self):
s = 'and the number is -42e-07, as expected'
m = self.re.search(s)
self.assertEqual(-42e-07, float(m.groupdict()['nbr']))
def test_number_8(self):
s = 'and the number is 42.3e+07, as expected'
m = self.re.search(s)
self.assertEqual(42.3e7, float(m.groupdict()['nbr']))
def test_number_9(self):
s = 'and the number is -42.3e-07, as expected'
m = self.re.search(s)
self.assertEqual(-42.3e-7, float(m.groupdict()['nbr']))
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment