Sunday 15 May 2011

regex - Python: re module to replace digits of telephone with asterisk -



regex - Python: re module to replace digits of telephone with asterisk -

this question has reply here:

python re.sub replace matched content 3 answers

i want replace digits in middle of telephone regex failed. here code:

temp= re.sub(r'1([0-9]{1}[0-9])[0-9]{4}([0-9]{4})', repl=r'$1****$2', tel_phone) print temp

in output, shows: $1****$2

but want show this: 131****1234. how accomplish ? thanks

i think you're trying replace 4 digits nowadays in middle (four digits nowadays before lastly 4 digits) ****

>>> s = "13111111234" >>> temp= re.sub(r'^(1[0-9]{2})[0-9]{4}([0-9]{4})$', r'\1****\2', s) >>> print temp 131****1234

you might have seen $1 in replacement string in other languages. however, in python, utilize \1 instead of $1. correctness, need include starting 1 in first capturing group, output include starting 1; otherwise, starting 1 lost.

python regex

No comments:

Post a Comment