[blivet:master] Add ability to match scientific notation in strings.

mulhern amulhern at redhat.com
Mon Feb 16 19:14:08 UTC 2015


The matching regular expression is expanded to include possible
scientific notation in numeric part and to exclude numeric parts
with multiple radices.

Uses named groups instead of indices.

Signed-off-by: mulhern <amulhern at redhat.com>
---
 blivet/size.py     |  9 +++------
 tests/size_test.py | 10 ++++++++++
 2 files changed, 13 insertions(+), 6 deletions(-)

diff --git a/blivet/size.py b/blivet/size.py
index da44343..6836566 100644
--- a/blivet/size.py
+++ b/blivet/size.py
@@ -173,19 +173,16 @@ def _parseSpec(spec):
     if radix != '.':
         spec = spec.replace(radix, '.')
 
-    # Match the string using only digit/space/not-space, since the
-    # string might be non-English and contain non-letter characters
-    # that Python doesn't understand as parts of words.
-    m = re.match(r'(-?\s*[0-9.]+)\s*([^\s]*)$', spec.strip())
+    m = re.match(r'(?P<numeric>(-|\+)?\s*(?P<base>([0-9]+)|([0-9]*\.[0-9]+)|([0-9]+\.[0-9]*))(?P<exp>(e|E)(-|\+)[0-9]+)?)\s*(?P<rest>[^\s]*)$', spec.strip())
     if not m:
         raise ValueError("invalid size specification", spec)
 
     try:
-        size = Decimal(m.groups()[0])
+        size = Decimal(m.group('numeric'))
     except InvalidOperation:
         raise ValueError("invalid size specification", spec)
 
-    specifier = m.groups()[1]
+    specifier = m.group('rest')
 
     # First try to parse as English.
     try:
diff --git a/tests/size_test.py b/tests/size_test.py
index e60c6d1..2bcdc84 100644
--- a/tests/size_test.py
+++ b/tests/size_test.py
@@ -184,6 +184,16 @@ class SizeTestCase(unittest.TestCase):
         self.assertEquals(Size("%s KiB" % (1/1025.0,)), Size(0))
         self.assertEquals(Size("%s KiB" % (1/1023.0,)), Size(1))
 
+    def testNoUnitsInString(self):
+        self.assertEqual(Size("1024"), Size("1 KiB"))
+
+    def testScientificNotation(self):
+        self.assertEqual(size._parseSpec("1e+0 KiB"), Decimal(1024))
+        self.assertEqual(size._parseSpec("1e-0 KiB"), Decimal(1024))
+        self.assertEqual(size._parseSpec("1e-1 KB"), Decimal(100))
+        self.assertEqual(size._parseSpec("1E-4KB"), Decimal("0.1"))
+        self.assertEqual(Size("1E-10KB"), Size(0))
+
 class TranslationTestCase(unittest.TestCase):
 
     def __init__(self, methodName='runTest'):
-- 
1.9.3



More information about the anaconda-patches mailing list