Split a number in chunks of 2 or 3 using regex (python)

Viewed 71

Say I have a phone number +9812345678 and +99123456789. I want to split it in ["+98","12","34","56,"78"] and ["+99","12","34","56","789"] i.e: "Start with +99 or +98 and then split in groups of atleast two and max 3"

I have tried something like:

import re
a = "+9812345678"
re.compile("(\+9[98])(\d{2,3})+")

which gives

['', '+98', '78', '']

that is a bit wrong.

1 Answers

Do not use re.split, use re.findall:

re.findall(r'^\+9[98]|\d{2}(?:\d$)?', text)

See the regex demo. Details

  • ^\+9[98] - start of string, +, 9 and then 9 or 8
  • | - or
  • \d{2} - two digits
  • (?:\d$)? - an optional sequence of a digit at the end of a string.

See the Python demo:

import re
texts = ['+9812345678','+99123456789']
for s in texts:
    print(re.findall(r'^\+9[98]|\d{2}(?:\d$)?', s))
# => ['+98', '12', '34', '56', '78']
#    ['+99', '12', '34', '56', '789']
Related