How to extract specific from the url using regex?

by ryan.murray , in category: Third Party Scripts , a day ago

How to extract specific from the url using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 15 hours ago

@ryan.murray 

To extract specific information from a URL using regex, you can use regular expressions to match patterns in the URL. Here is an example in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import re

url = "https://www.example.com/page?id=12345&name=john"

# Extracting the id from the URL
id_match = re.search(r'id=(d+)', url)
if id_match:
    id_value = id_match.group(1)
    print("ID:", id_value)

# Extracting the name from the URL
name_match = re.search(r'name=([a-zA-Z]+)', url)
if name_match:
    name_value = name_match.group(1)
    print("Name:", name_value)


In this example, we use regular expressions to match the patterns "id=" and "name=" followed by the corresponding values in the URL. The re.search function returns a match object, from which we extract the desired value using the group method.


You can customize the regular expressions based on the specific patterns you are looking to match in the URL.