keep the first part of the URL and mask everything else

Viewed 64

How do I keep the first (domain) part of the URL and mask everything else after that?

This does not work:

s= ' Get exciting offers when you book a XX year car   June XX - XXXX Click here to book http://abc.in/XXzOK '

import re
formatting = [
    [r"http://abc.in/", "http://abc.in/XXXX"]
]

for regex,substitution in formatting:
    s = re.sub(regex, substitution, s)
    print (s)

The domain name can be anything like google.com or yahoo.com

Expected result:

Get exciting offers when you book a XX year car   June XX - XXXX Click here to book http://abc.in/XXXXX
2 Answers

For the example, You could put \S* after the regex as you can see in this demo but then you would have to list all of the replacements.

One option for more urls could be using 2 groups, and could the number of characters in the second group replacing those by X

Or just replace the match after group 1 with XXXX without using group 2 in the pattern if it should be a fixed string in the replacement.

import re

s= ' Get exciting offers when you book a XX year car   June XX - XXXX Click here to book http://abc.in/XXzOK '    
s = re.sub(r"(https?://[^/\s]+/)(\S+)", lambda x: x.group(1) + 'X' * len(x.group(2)), s)

print(s)

Output

 Get exciting offers when you book a XX year car   June XX - XXXX Click here to book http://abc.in/XXXXX 

Python demo

Use

import re
s = ' Get exciting offers when you book a XX year car   June XX - XXXX Click here to book http://abc.in/XXzOK '
s = re.sub(r'(https?://[^/]+/)\S*', r'\1XXXX', s)
print(s)

See Python proof

Regex:

(https?://[^/]+/)\S*

See regex proof.

EXPLANATION

NODE EXPLANATION
( group and capture to \1:
http 'http'
s? 's' (optional (matching the most amount possible))
:// '://'
[^/]+ any character except: '/' (1 or more times (matching the most amount possible))
/ '/'
) end of \1
\S* non-whitespace (all but \n, \r, \t, \f, and " ") (0 or more times (matching the most amount possible))
Related