0

I have a few strings:

strings = [
'some.code(user, password="aA1$")',
'some.code("a1", passwd="aA1$", c=0)',
"some.code(user, passw='aA1$')\n",
]

I want to use python regex to replace all passwords with asterisks (*) like so:

some.code(username, password="****")
some.code("a1", passwd="****", c=0)
some.code(username, passw='****')

I got as far as this however I still have to use python string "replace" method:

pattern = r'\bpass\w+=[\'|\"](.+?)[\'|\"]'
for s in strings:
    password = re.search(pattern, s).group(1)
    print(s.replace(password, '*'*len(password)))

Output:

some.code(user, password="****")
some.code("a1", passwd="****", c=0)
some.code(user, passw='****')

Is there a way to achieve the same with a regex pattern?

Maugrim
  • 126
  • 6
  • you can use re.sub(pattern, replacement, string), but you would then not see the amount of characters the user typed. So the solution you have seems good to me. Doubt you can do it much more shoter than this – tst Nov 26 '19 at 12:30
  • `pattern = r'\b(pass\w+=[\'"])(.+?)([\'"])'`, and then `re.sub(pattern, lambda x: "{}{}{}".format(x.group(1),'*'*len(x.group(2)),x.group(3)), s)`, see https://ideone.com/qsUMMO – Wiktor Stribiżew Nov 26 '19 at 12:33

0 Answers0