Python 程序检查字符串中是否存在 URL
本文将教你如何确定字符串是否包含 URL。在 Python 中,字符串是表示 Unicode 字符的字节集合。您可以使用单引号或双引号,其中包含的所有内容都被视为字符串。给定一个字符串,我们将首先确定它是否包含 URL。如果找到一个,我们将打印该 URL。
使用 findall() 方法
我们将使用 Python 的正则表达式概念来解决此问题。正则表达式由 Python 的 re 包支持。正则表达式是一系列特殊的字符,使用模式中定义的特定语法来帮助匹配或查找其他字符串或字符串集。
findall() 方法返回的列表中的每个字符串都表示找到的不同匹配项。此方法通过从左到右扫描字符串来按找到的顺序返回匹配项。
算法
以下算法演示了如何使用 findall() 方法检查字符串中是否存在 url:
导入 re 模块
创建一个函数来查找 URL。
在函数中创建一个正则表达式,该表达式存储 URL 中可能包含的每个字符。
声明第二个变量,该变量将存储符合 URL 模式的每个字符串。
一次打印列表中的所有字符串。
声明一个包含字符的字符串。
将字符串传递到函数后,打印函数返回的值。
示例
在此程序中,我们使用了 re 模块方法,该方法将在提供的字符串中搜索指定的模式。为了使用该方法,我们必须将 re 模块导入程序。如果字符串不包含任何 URL,则程序将显示一个空列表。
import re
def checkURL(str):
# findall() function used with the conditions which is valid for url in the strings
# The regex function can store all the characters including the upper case and the lower case of the alphabets, numbers, special cases and characters etc 8. Python program to check for url in a string
regex= 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
URL= re.findall(regex,str)
return URL
# The driver code
m = "https://tutorialspoint.com/python-program-to-check-for-url-in-a-string"
print("The url is: ", checkURL(m))
输出
以下是上述代码的输出:
The url is: ['https://tutorialspoint.com/python-program-to-check-for-url-in-a-string']
示例
在下面提到的 Python 代码中,我们为 URL 创建了一个正则表达式来验证字符串中的 URL,并且我们使用内置方法 findall() 来检查输入字符串中的 URL 模式。在 findall() 函数从左到右扫描字符串后返回结果:
import re
def checkURL(str):
# findall() function used with the conditions which is valid for url in the strings
regex= 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
checkURL= re.findall(regex,str)
if checkURL:
return "url in the string is : ",checkURL
else:
return "URL is not present"
# The driver code
m = input("Provide the string: ")
print(checkURL(m))
输出
以下是两种输出情况:
情况 1
当未正确提供 url 模式时,以下是上述代码的输出:
Provide the string: Providing this like url The url is: URL is not present
情况 2
当正确提供 url 时,以下是输出:
Provide the string: https://tutorialspoint.com/python-program-to-check-for-url-in-a-string
('url in the string is : ', ['https://tutorialspoint.com/python-program-to-check-for-url-in-a-string'])
使用 search() 方法
Python 中的正则表达式搜索通常表示为:match = re.search (path, string)。re.search() 方法使用正则表达式模式和字符串在字符串中查找正则表达式模式。如果搜索成功,则 search() 返回一个匹配对象或 None。
示例
下面给出的代码中使用了 re 模块的 search() 方法,该方法将所需的结果作为 URL 返回:
import re
# findall() function used with the conditions which is valid for url in the strings
string = "https://tutorialspoint.com/python-program-to-check-for-url-in-a-string"
regex= 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
result = re.search(regex,string).group()
print("The URL is: ", result)
输出
以下是上述代码的输出:
The URL is: https://tutorialspoint.com/python-program-to-check-for-url-in-a-string
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP