亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python正則表達式從IP字符串中刪除端口號

Python正則表達式從IP字符串中刪除端口號

一只名叫tom的貓 2023-08-08 16:31:56
我有一個文本文件,其中包含文本行和帶端口號的 IP,我想刪除端口號并僅打印 IP。文本文件示例:77.55.211.77:8080無IP79.127.57.42:80期望的輸出:77.55.211.7779.127.57.42我的代碼:import rewith open('IPs.txt', 'r') as infile:     for ip in infile:        ip = ip.strip('\n')        IP_without_port_number = re.sub(r'((?::))(?:[0-9]+)$', "", ip)        re_for_IP = re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',ip)        print(IP_without_port_number)我不明白為什么當我打印到控制臺“IP_without_port_number”時我看到所有行作為輸出
查看完整描述

4 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

您所需要的只是第二場比賽:


import re


with open('IPs.txt', 'r') as infile:

    for ip in infile:

        re_for_IP = re.match(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', ip)

        if re_for_IP:

            print(re_for_IP[0])

輸出:


77.55.211.77

79.127.57.42

單線:


import re


ips = []


with open('IPs.txt', 'r') as infile:

    ips = [ip[0] for ip in [re.match(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', ip) for ip in infile] if ip]


print(ips)


查看完整回答
反對 回復 2023-08-08
?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

我想出了這個正則表達式代碼,它對我有用而且很簡單。


import re

text = input("Input text: ")

pattern = re.findall(r'\d+\.\d+\.\d+\.\d+', text)

print(pattern)


查看完整回答
反對 回復 2023-08-08
?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

您不需要正則表達式,:在讀取該行時對字符使用 split 函數。然后您將得到一個包含兩個位置的數組,第一個僅包含 IP 地址,另一個包含端口。



查看完整回答
反對 回復 2023-08-08
?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

嘗試這個:


import re

regex = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 

            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 

            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 

            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$'''


with open('IP.txt', 'r') as infile: 

    for ip in infile:

        ip = ip.strip('\n')

        IP_without_port_number = re.sub(r':.*$', "", ip)

        re_for_IP = re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',ip)

        if(re.search(regex, IP_without_port_number)):  

            print(IP_without_port_number)

輸出:


77.55.211.77

79.127.57.42


查看完整回答
反對 回復 2023-08-08
  • 4 回答
  • 0 關注
  • 624 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號