I have a problem because a password is printed out in a log. I can't control the source of the log so my only option is to do a replacement.
I have the following string a = "http://user:password@someurl.ip.com"
I want to replace the password with "*****"
using a regex
something like
b = re.sub('(?<=:)(.*?)(?=@)', '********', a)
my problem is that I'm matching from the first ":"
so I'm replacing "//user:password"
instead of "password"
How can I tune my regex to achieve what I want?
You can rule out matching a :
and @
using a negated character class:
(?<=:)[^:@]+(?=@)
import re
a = "http://user:password@someurl.ip.com"
b = re.sub('(?<=:)[^:@]+(?=@)', '********', a)
print(b)
Output
http://user:********@someurl.ip.com
Or perhaps use a bit more specific match using a capture group to match the protocol:
import re
a = "http://user:password@someurl.ip.com"
b = re.sub(r"\b(https?://[^:]+:)[^:@]+(?=@)", r"\1********", a)
print(b)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.