How to replace url parts with regex in python?

Member

by mac , in category: Third Party Scripts , 4 months ago

How to replace url parts with regex in python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 4 months 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.

Related Threads:

How to replace a substring with a regex pattern using regex in python?
How to replace part of a url with regex?
How to split string into parts using regex?
How to replace string by regex?
How to replace all occurrences by regex?
How to replace a specific character in regex?