fork download
  1. import re
  2. texts = ['The 3rd box marked 4 cannot exceed 7.34kg but if its exact 8.42kg its okay too',
  3. 'The 3 boxes with red on them must not exceed -23.4435kg and don\'t pick them up.',
  4. 'Parcels that can be sent are limited by 1,402kg and its okay to send',
  5. 'The 2 boxes on the shelf must not exceed: \n102 kg',
  6. 'Do not pick up 18 boxes at a time and make sure they cannot exceed,: 92302 k.g',
  7. 'Do not pick up boxes that weight 56.23 kg',
  8. 'Boxes cannot exceed -23 k/g',
  9. 'must not exceed -23.4435kg']
  10.  
  11. rx = re.compile(r'\b((?:must\s+|can)not\s+exceed|limited\s+by)\W*?(-?\d+(?:,\d+)*(?:\.\d+)?)\s*(kg|k\.g|k/g)\b')
  12. for text in texts:
  13. print("----", text,"----")
  14. m = rx.search(text)
  15. if m:
  16. print(f"Phrase: {m.group(1)}")
  17. print(f"Number: {m.group(2)}")
  18. print(f"UOM: {m.group(3)}")
  19. else:
  20. print("Not matched!")
Success #stdin #stdout 0.03s 9636KB
stdin
Standard input is empty
stdout
---- The 3rd box marked 4 cannot exceed 7.34kg but if its exact 8.42kg its okay too ----
Phrase: cannot exceed
Number: 7.34
UOM: kg
---- The 3 boxes with red on them must not exceed -23.4435kg and don't pick them up. ----
Phrase: must not exceed
Number: -23.4435
UOM: kg
---- Parcels that can be sent are limited by 1,402kg and its okay to send ----
Phrase: limited by
Number: 1,402
UOM: kg
---- The 2 boxes on the shelf must not exceed: 
102 kg ----
Phrase: must not exceed
Number: 102
UOM: kg
---- Do not pick up 18 boxes at a time and make sure they cannot exceed,: 92302 k.g ----
Phrase: cannot exceed
Number: 92302
UOM: k.g
---- Do not pick up boxes that weight 56.23 kg ----
Not matched!
---- Boxes cannot exceed -23 k/g ----
Phrase: cannot exceed
Number: -23
UOM: k/g
---- must not exceed -23.4435kg ----
Phrase: must not exceed
Number: -23.4435
UOM: kg