Calculate Sum Get User Input Patterns Program Find Area of CircleFind Area of Rectangle Perimeter of Rectangle Find Even and Odd Numbers Find Sum of Digit in Python Find Factorial in PythonPrint Fibonacci Series Check Armstrong Number Reverse a Number Check Palindrome Number Swap Two Numbers Matrix MultiplicationFind Perfect NumberAdd Two Matrix in Python Find Sum of Squares Find Sum of Cubes Find URL in String
Find Largest in List Find Duplicate in List Check Alphabet Remove Duplicate Elements from List Reverse List Elements Find Element in Python List Interchange first and last element in List Find Even Numbers in List Find Length of a List Find Sum of list Elements Find Elements in List Get the product of List elements Interchange List Elements Find Smallest Elements in List Find Max Value in a List
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.
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/']
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/