[英]How to grab first ip address from a string
我正在嘗試從字符串中獲取ip address
並遇到問題。請幫忙。
inet addr:11.11.11.11 Bcast:11.11.11.111 Mask:111.111.11.1
。
這是我擁有的字符串,我需要在 addr 旁邊的 ip 地址:
我嘗試了以下代碼,但在 python 中失敗:
ip = re.findall(r'(?:\\d{1,3}\\.)+(?:\\d{1,3})', line)
並獲得索引 0 的項目。
結果:這實際上沒有給我任何回報
您的REGEX可能更具體,我想您可以使用類似:
addr:(?<ip>\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})
在python中:
match = re.match(r'addr:(?<ip>\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})', line)
然后,您可以通過調用match.group('ip')
來訪問ip
組。
我注意到您的正則表達式將匹配無效的IPv4地址。
import re
string = 'inet addr:300.11.11.11 Bcast:11.11.11.111 Mask:111.111.11.1'
# your pattern
ip_address_pattern = re.compile(r'(?:\d{1,3}\.)+(?:\d{1,3})')
find_ip_address = re.findall(ip_address_pattern, string)
if find_ip_address:
print (find_ip_address)
# outputs
['300.11.11.11', '11.11.11.111', '111.111.11.1']
我過去曾使用過此IPv4_format來提取有效的IPv4地址。
import re
string = 'inet addr:11.11.11.11 Bcast:11.11.11.111 Mask:111.111.11.1'
# Valid IPv4 address format
ip_address_pattern = re.compile(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b')
find_ip_address = re.findall(ip_address_pattern, string)
if find_ip_address:
print (find_ip_address)
# outputs
['11.11.11.11', '11.11.11.111', '111.111.11.1']
import re
line = "inet addr:11.11.11.11 Bcast:11.11.11.111 Mask:111.111.11.1"
pattern = r"[\d]{2}[.][\d]{2}[.][\d]{2}[.][\d]{2}[\D]"
re.findall(pattern, line)
['11.11.11.11 ']
re.findall(pattern, line)[0].strip()
'11.11.11.11'
如果列表中有多個元素,只需使用.strip()
運行list-comp
[i.strip() for i in re.findall(pattern, line)]
['11.11.11.11']
re.match()
無法正常工作,因為它將嘗試從字符串的開頭開始匹配您的模式(請注意,您的模式不包含“ inet addr: ”部分。
re.search()
可以工作,但是它會丟失重復出現的元素,並且僅在成功匹配后才返回模式的首次匹配,此外,您還必須使用filter
來提取元素。
最后,解決此問題的關鍵在於目標的最后一個字符xx.xx.xx.xx[\\D]
。 [\\D]
指令可確保模式在索引12處查找無整數, [\\s]
同樣有效,並且與空格匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.