fork download
  1. import re
  2. my_strings = ["po box 12 34 5 heisenburg 902 rr 15", "po box 12 59 76","po box 56 56 barry 56 87","barry box 56 87"]
  3. p = re.compile(r'\b(po\s+box\s*)(\d+(?:\s+\d+)+)')
  4. for s in my_strings:
  5. print(s, ' => ', p.sub(lambda x: f"{x.group(1)}{''.join(c for c in x.group(2).split())}", s))
Success #stdin #stdout 0.02s 9536KB
stdin
Standard input is empty
stdout
po box 12 34 5 heisenburg 902 rr 15  =>  po box 12345 heisenburg 902 rr 15
po box 12 59 76  =>  po box 125976
po box 56 56 barry 56 87  =>  po box 5656 barry 56 87
barry box 56 87  =>  barry box 56 87