fork download
  1. import re
  2.  
  3. text = """cakes 10 are good.
  4. cakes 10c are good.
  5. cakes 20 21 22 are good.
  6. cakes 30, 31, 32 are good.
  7. cakes 40a, 40b, 40c are good."""
  8.  
  9. numerical = r"""
  10. [0-9]{1,4}((\.|\-)?[A-Za-z])? # max 4 digits followed optionally by a letter separated by , or - optionally.
  11. """
  12.  
  13. # those could be separated by:
  14. separator = r"""(,?\s?)""" # comma followed optionally by space
  15.  
  16. # code to get the matches with finditer
  17. pattern2 = fr"""(({numerical}
  18. (({separator})?|\s?))+
  19. |
  20. {numerical} # single case
  21. )"""
  22. refs = re.finditer(pattern2, text, re.VERBOSE, )
  23. for element in refs:
  24. print(element.group())
Success #stdin #stdout 0.04s 9472KB
stdin
Standard input is empty
stdout
10 
10c 
20 21 22 
30, 31, 32 
40a, 40b, 40c