Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python ตรวจสอบ URL ในสตริงด้วย regex


ใช้โมดูล re และ findall() ค้นหา URL ในสตริง

อัลกอริทึม

  1. รับสตริง
  2. ใช้ re.findall() กับ regex pattern สำหรับ URL
  3. คืนรายการ URL ที่พบ

โค้ดตัวอย่าง

import re

def url(str):
    ur = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', str)
    return ur

str = 'https://auth.mywebsite.org / user / python program / https://www.mywebsite.org/'
print("Url is:", url(str))

ผลลัพธ์

Url is: ['https://auth.mywebsite.org / user / python program / https://www.mywebsite.org/']