Browse Source

Sum.parse_text: accept arbitrary number of digits after comma separator

Fabian Peter Hammerle 7 years ago
parent
commit
d2d02b200f
3 changed files with 18 additions and 14 deletions
  1. 16 13
      finoex/__init__.py
  2. 1 1
      setup.py
  3. 1 0
      tests/test_sum.py

+ 16 - 13
finoex/__init__.py

@@ -91,25 +91,28 @@ class Sum(ioex.calcex.Figure):
     unit = property(get_unit, set_unit)
     currency = property(get_unit, set_unit)
 
-    value_regex = r"-?\d+([\.,]\d{2})?"
+    value_regex = r"-?\d+([\.,]\d+)?"
     currency_regex = r"[^\d\s-]+"
 
+    sum_regex = [
+        r'^\$?(?P<value>{}) (?P<curr>{})$'.format(
+            value_regex, currency_regex,
+        ),
+        r'^(?P<curr>{}) ?(?P<value>{})$'.format(
+            currency_regex, value_regex,
+        ),
+    ]
+
     @staticmethod
     def parse_text(text):
-        match = re.search(
-            r'^\$?(?P<value>{}) (?P<curr>{})$'.format(
-                Sum.value_regex, Sum.currency_regex),
+        for pattern in Sum.sum_regex:
+            match = re.search(pattern, text, re.UNICODE)
+            if match:
+                break
+        assert not match is None, '\n{}\ntext: {!r}'.format(
+            '\n'.join(Sum.sum_regex),
             text,
-            re.UNICODE,
         )
-        if not match:
-            match = re.search(
-                r'^(?P<curr>{}) ?(?P<value>{})$'.format(
-                    Sum.currency_regex, Sum.value_regex),
-                text,
-                re.UNICODE,
-            )
-        assert not match is None, text
         attr = match.groupdict()
         return Sum(
             value=locale.atof(attr['value']),

+ 1 - 1
setup.py

@@ -4,7 +4,7 @@ import glob
 
 setup(
     name = 'finoex',
-    version = '0.7.0',
+    version = '0.7.1',
     # description = '',
     author = 'Fabian Peter Hammerle',
     author_email = 'fabian.hammerle@gmail.com',

+ 1 - 0
tests/test_sum.py

@@ -95,6 +95,7 @@ def test_mul(dividend, divisor, quotient):
     ['en_US.UTF-8', "-1.23 US$", finoex.Sum(-1.23, 'USD')],
     ['en_US.UTF-8', "-1.23 USD", finoex.Sum(-1.23, 'USD')],
     ['en_US.UTF-8', "1.23 ¥", finoex.Sum(1.23, 'CNY')],
+    ['en_US.UTF-8', "2.2 US$", finoex.Sum(2.2, 'US$')],
     ['en_US.UTF-8', "2.50 EUR", finoex.Sum(2.5, 'EUR')],
     ['en_US.UTF-8', "2.50 €", finoex.Sum(2.5, 'EUR')],
     ['en_US.UTF-8', "US$-0.50", finoex.Sum(-0.5, 'USD')],