irc irc - 1 year ago 105
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 +



should produce,


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 Source

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

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

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

>>> from itertools import dropwhile
>>> not_allowed = {'0', '*', '#', '+'}
>>> ''.join(dropwhile(lambda x: x in not_allowed, s))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download