簡體   English   中英

Python正則表達式/結果中間詞

[英]Python Regular Expression / Middle word in result

我有不必要的結果字符串的問題。 我只想從文件中提取https。 我的代碼是:

import sys
import os
import hashlib
import re

if len(sys.argv) < 2 :
    sys.exit('Aby uzyc wpisz: python %s filename' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('BLAD!: Plik "%s" nie znaleziony!' % sys.argv[1])

with open(sys.argv[1], 'rb') as f:
    plik = f.read()
    print("MD5: %s" % hashlib.md5(plik).hexdigest())
    print("SHA1: %s" % hashlib.sha1(plik).hexdigest())
    print("SHA256: %s" % hashlib.sha256(plik).hexdigest())
    print("Podejrzane linki: \n")
    pliki = open(sys.argv[1], 'r')
    for line in pliki:
        if re.search("(H|h)ttps:(.*)",line):
            print(line)
        elif re.search("(H|h)ttp:(.*)",line):
            print(line)
    pliki.close()

結果:

MD5: f16a93fd2d6f2a9f90af9f61a19d28bd
SHA1: 0a9b89624696757e188412da268afb2bf5b600aa
SHA256: 3b365deb0e272146f00f9d723a9fd4dbeacddc10123aec8237a37c10c19fe6df
Podejrzane linki: 

        GrizliPolSurls = "http://xxx.xxx.xxx.xxx" 

        FilnMoviehttpsd.Open "GET", "https://xxx.xxx.xxx.xxx",False

我只想輸入""字符串,並且從httphttps開頭,例如http://xxx.xxx.xxx.xxx

所需結果:

MD5: f16a93fd2d6f2a9f90af9f61a19d28bd
SHA1: 0a9b89624696757e188412da268afb2bf5b600aa
SHA256: 3b365deb0e272146f00f9d723a9fd4dbeacddc10123aec8237a37c10c19fe6df
Podejrzane linki: 
http://xxx.xxx.xxx.xxx
https://xxx.xxx.xxx.xxx

您可以將re.findall與以下正則表達式一起使用(在regex101上進行了說明 ):

"([Hh]ttps?.*?)"

所以:

import re
s = '''MD5MD5:: f16a93fd2d6f2a9f90af9f61a19d28bd
SHA1 f16a93fd2 : 0a9b89624696757e188412da268afb2bf5b600aa
SHA256: 3b365deb0e272146f00f9d723a9fd4dbeacddc10123aec8237a37c10c19fe6df
Podejrzane linki: 

        GrizliPolSurls = "http://xxx.xxx.xxx.xxx" 

        FilnMoviehttpsd.Open "GET", "https://xxx.xxx.xxx.xxx",False'''
urls = re.findall('"([Hh]ttps?.*?)"', s)
#['http://xxx.xxx.xxx.xxx', 'https://xxx.xxx.xxx.xxx']

您需要以下模式: (?<=")http[^"]+

(?<=") -正向后看,以確定"是否在當前位置之前。

http -比賽http字面上。

[^"]+ -匹配所有內容,直到"為止,這是一種反類技術,以避免使用量詞:)

演示

re.search()返回一個Match對象

您必須從結果中獲取信息:

line = "my text line contains a http://192.168.1.1 magic url"
result = re.search("[Hh]ttps?://\d+\.\d+\.\d+\.\d+", line)
print(result.group())  # will print http://192.168.1.1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM