TitanFighter TitanFighter - 2 months ago 8
Python Question

How to split string with different phones using re?

For example there are such phones:

phones = '+35(123) 456 78 90 (123) 555 55 55 (908)985 88 89 (593)592 56 95'


I need to get:

phones_list = ['+35(123) 456 78 90', '(123) 555 55 55', '(908)985 88 89', (593)592 56 95]


Trying to solve using
re
, but quite a hard task to me.

Answer

This approach uses the + or ( to signal the beginning of a phone number. It does not require multiple-spaces:

>>> phones = '+35(123) 456 78 90 (123) 555 55 55  (908)985 88 89   (593)592 56 95'
>>> re.split(r' +(?=[(+])', phones)
['+35(123) 456 78 90', '(123) 555 55 55', '(908)985 88 89', '(593)592 56 95']

This splits the string based on one-or-more spaces followed by either ( or +.

In the regular expression, + matches one or more spaces. (?=[(+]) is a look-ahead. It requires that the spaces be followed by either ( or + but does not consume the ( or +. Because we are using a look-ahead instead of a plain match, the the leading ( and + remain part of the phone number.

Comments