How to replace url parts with regex in python?

Member

by mac , in category: Third Party Scripts , 2 days ago

How to replace url parts with regex in python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 2 days ago

@mac 

To replace parts of a URL using regex in Python, you can use the re.sub() function from the re module. Here's an example:

1
2
3
4
5
6
import re

url = "https://www.example.com/page1?param=value"
new_url = re.sub(r'/page1', '/newpage', url)

print(new_url)


In this example, the re.sub() function replaces the part of the URL that matches the regex pattern '/page1' with '/newpage'. You can customize the regex pattern to match specific parts of the URL that you want to replace.