Python | Check for URL in a String
Prerequisite : Pattern matching with Regular Expression
In this article, we will need to accept a string and we need to check if the string contains any URL in it. If the URL is present in the string, we will say URL’s been found or not and print the respective URL present in the string. We will use the concept of Regular Expression of Python to solve the problem.
Examples:
Input : string = 'My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of http://www.geeksforgeeks.org/' Output : URLs : ['https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles', 'http://www.geeksforgeeks.org/'] Input : string = 'I am a blogger at https://geeksforgeeks.org' Output : URL : ['https://geeksforgeeks.org']
To find the URLs in a given string we have used the findall() function from the regular expression module of Python. This return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.
# Python code to find the URL from an input string # Using the regular expression import re def Find(string): # findall() has been used # with valid conditions for urls in string url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+] |[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string) return url # Driver Code string = 'My Profile: https://auth.geeksforgeeks.org / user / Chinmoy % 20Lenka / articles in the portal of http://www.geeksforgeeks.org/' print("Urls: ", Find(string)) |
Output:
Urls: ['https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles', 'http://www.geeksforgeeks.org/']
Recommended Posts:
- String slicing in Python to check if a string can become empty by recursive deletion
- Python | Check if given string can be formed by concatenating string elements of list
- Python | Check if string ends with any string in given list
- Python | Check if a given string is binary string or not
- Python | Check whether string contains only numbers or not
- Python | Check if a variable is string
- Python | Check for spaces in string
- Python | Check if given string is numeric or not
- Python | Check if string repeats itself
- Python | Check for ASCII string
- Python set to check if string is panagram
- Python | Check for float string
- Python Set | Check whether a given string is Heterogram or not
- How to check if a string is a valid keyword in Python?
- Check if both halves of the string have same set of characters in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



