Python 检查字符串中的URL

Python 检查字符串中的URL

本文将教你如何确定一个字符串是否包含URL。在Python中,字符串是代表Unicode字符的字节集合。你可以使用单引号或双引号,其中的所有内容都被视为字符串。给定一个字符串,我们首先确定它是否包含URL。如果找到一个URL,我们将打印出该URL。

使用findall()方法

我们将使用Python的正则表达式概念来解决这个问题。正则表达式由Python re包支持。使用模式中定义的特定语法,正则表达式是一系列特殊字符的序列,用于匹配或查找其他字符串或字符串集。

findall()方法返回的列表中的每个字符串表示找到的不同匹配。该方法从左到右扫描字符串,按照找到的顺序返回匹配项。

步骤

下面的算法演示了如何使用findall()方法在字符串中检查URL:

  • import 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://www.tutorialspoint.com/python-program-to-check-for-url-in-a-string" 
print("The url is: ", checkURL(m))

输出

以下是上述代码的输出-

The url is:  ['https://www.tutorialspoint.com/python-program-to-check-for-url-in-a-string']

示例

在下面提到的Python代码中,我们创建了一个用于验证字符串中的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://www.tutorialspoint.com/python-program-to-check-for-url-in-a-string
('url in the string is : ', ['https://www.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://www.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://www.tutorialspoint.com/python-program-to-check-for-url-in-a-string

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程