Javaexercise.com

Python Program: How To Find URL in Python String?

To find a URL(Uniform Resource Locator) in a String, Python provides several built-in methods that can help us. Here, we will use the re module of Python that provides several methods such as 

  • findall() method

  • search() method

The findall() method is used to get a list of all possible matches of patterns in a string whereas the search() method returns the first location where this regular expression produces a match.

Let's get started and see the use of these methods with the help of program examples. 

Program To Find URL in String in Python

In this program, we used findall() method that takes the first argument as a regex and the second is a string in which we will find the URL. It returns a list of possible matches. See the code example.

# Python Program to find URL in String
import re

# Take a string containing URL
string = "Python Programs: https://www.javaexercise.com/"

# Apply regex to filter the URL
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
url = re.findall(regex,string)
result = [x[0] for x in url]

# Display Result
print("Urls: ", result)

Output;

Urls:  ['https://www.javaexercise.com/']

 

Program To Find URL in String using search() Method in Python

In this program, we used the search() method of re module that returns the desired result as URL. See the code below.

# Python Program to find URL in String
import re

# Take a string containing URL
string = "Visit at : https://www.javaexercise.com/"

# Apply regex to filter the URL
result = re.search("(?P<url>https?://[^\s]+)", string).group("url")

# Display Result
print("Urls: ", result)

Output:

Urls:  https://www.javaexercise.com/

 

Useful References: