-1

I want to replace the digits in the middle of telephone with regex but failed. Here is my 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 the output, it always shows: $1****$2

But I want to show like this: 131****1234. How to accomplish it ? Thanks

user1179442
  • 473
  • 5
  • 16

1 Answers1

2

I think you're trying to replace four digits present in the middle (four digits present before the last four digits) with ****

>>> 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, use \1 instead of $1. For correctness, you also need to include the starting 1 in the first capturing group, so that the output also include the starting 1; otherwise, the starting 1 will be lost.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • I didn't downvote. However you should explain "why" OP would be trying to "get like this" ... Your answer does not explain anything wrong about OPs replacement which is the main cause of the problem. – hwnd Oct 20 '14 at 03:51
  • +1 why people downvote an answer that works? For example, I learn best by example, all I would have needed to see is `r'\1****\2'` to get the idea that `r"$1****$2"` is wrong and how to use numbered captured groups in other cases. I'm sure I'm not alone. – jfs Oct 20 '14 at 03:54