irc irc - 4 months ago 9
Python Question

Regex to strip only start of string

I am trying to match phone number using regex by stripping unwanted prefixes like 0, *, # and +

e.g.

+*#+0#01231340010


should produce,

1231340010


I am using python re module

I tried following,

re.sub(r'[0*#+]', '', '+*#+0#01231340010')


but it is removing later 0s too.

I tried to use regex groups, but still it's not working ( or I am doing something wrong for sure ).

Any help will be appreciated.

Thanks in advance.

Answer

Add the start of the string check (^) and * quantifier (0 or more occurences):

>>> re.sub(r'^[0*#+]*', '', '+*#+0#01231340010')
'1231340010'

Or, a non-regex approach using itertools.dropwhile():

>>> from itertools import dropwhile
>>> not_allowed = {'0', '*', '#', '+'}
>>> ''.join(dropwhile(lambda x: x in not_allowed, s))
'1231340010'
Comments