w3resource logo
Python Exercises

Python: Find urls in a string

Python Regular Expression: Exercise-42 with Solution

Write a Python program to find urls in a string.

Sample Solution:-

Python Code:

import re
text = '<p>Contents :</p><a href="http://w3resource.com">Python Examples</a><a href="http://github.com">Even More Examples</a>'
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text)
print("Original string: ",text)
print("Urls: ",urls)

Sample Output:

Original string:  

Contents :

Python ExamplesEven More Examples Urls: ['http://w3resource.com', 'http://github.com']

Python Code Editor:

import re
text = '<p>Contents :</p><a href="http://w3resource.com">Python Examples</a><a href="http://github.com">Even More Examples</a>'
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text)
print("Original string: ",text)
print("Urls: ",urls)

Improve this sample solution and post your code through Disqus