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

輸出

以下是上述程式碼的輸出:

The url is:  ['https://tutorialspoint.tw/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.tw/python-program-to-check-for-url-in-a-string
('url in the string is : ', ['https://tutorialspoint.tw/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.tw/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.tw/python-program-to-check-for-url-in-a-string

更新時間: 2023 年 4 月 4 日

2K+ 閱讀量

啟動您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.