You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过正则反向匹配或Python提取IP对应的国家名称

提取对应IP的国家名:正则与Python实现方案

一、改进的正则表达式方案

1. 单个单词国家名匹配(如Canada、Japan)

如果目标国家名是单个无空格的单词,用这个正则可以精准匹配IP前的国家名:

(\S+)\s*\(111\.111\.111\.111\)
  • 核心逻辑:
    • \S+:匹配一个或多个非空白字符(即单个单词的国家名)
    • \s*:兼容国家名与IP括号之间的0个或多个空格
    • \(111\.111\.111\.111\):转义匹配包裹目标IP的括号和点符

2. 多单词国家名匹配(如United States、United Kingdom)

如果国家名包含空格,用非贪婪模式避免匹配冗余内容:

([^\(]+?)\s*\(111\.111\.111\.111\)
  • 核心逻辑:
    • [^\(]+?:非贪婪匹配任意非左括号的字符,直到遇到IP的左括号
    • 匹配后记得用strip()去除首尾多余空格

3. 反向匹配至首个空格(精准定位最近空格到IP间的内容)

如果需要严格从IP位置往前匹配到第一个空格,用反向后顾断言实现:

(?<=\s)([^\s].*?)(?=\s*\(111\.111\.111\.111\))
  • 核心逻辑:
    • (?<=\s):确保匹配内容的前一个字符是空格
    • [^\s].*?:从第一个非空格字符开始,非贪婪匹配到IP括号前
    • (?=\s*\(111...\)):确保匹配内容的后方是目标IP的括号形式

二、Python代码实现示例

示例1:单IP提取

import re

text = "Sample Text United States (111.111.111.111) Another Line Canada (222.222.222.222)"

# 提取111.111.111.111对应的国家名
pattern_1 = r'([^\(]+?)\s*\(111\.111\.111\.111\)'
match_1 = re.search(pattern_1, text)
if match_1:
    country1 = match_1.group(1).strip()
    print(f"Country1: {country1}")  # 输出: Country1: United States

# 提取222.222.222.222对应的国家名
pattern_2 = r'([^\(]+?)\s*\(222\.222\.222\.222\)'
match_2 = re.search(pattern_2, text)
if match_2:
    country2 = match_2.group(1).strip()
    print(f"Country2: {country2}")  # 输出: Country2: Canada

示例2:批量处理多IP

如果需要匹配多个目标IP,可构建动态正则一次性提取所有结果:

import re

text = "Sample Text United States (111.111.111.111) Another Line Canada (222.222.222.222) More Text Germany (333.333.333.333)"
target_ips = ["111.111.111.111", "222.222.222.222"]

# 转义IP并构建正则选择项
ip_pattern = '|'.join([re.escape(ip) for ip in target_ips])
full_pattern = rf'([^\(]+?)\s*\(({ip_pattern})\)'

# 提取所有匹配结果并整理为字典
matches = re.findall(full_pattern, text)
result = {ip: country.strip() for country, ip in matches}

print(result)
# 输出: {'111.111.111.111': 'United States', '222.222.222.222': 'Canada'}

示例3:无正则字符串分割实现

如果文本格式固定,也可以用字符串操作替代正则:

text = "Sample Text United States (111.111.111.111) Another Line Canada (222.222.222.222)"

# 提取Country1
ip1 = "111.111.111.111"
ip1_pos = text.find(f"({ip1})")
last_space = text.rfind(' ', 0, ip1_pos)
country1 = text[last_space+1:ip1_pos].strip()

# 提取Country2
ip2 = "222.222.222.222"
ip2_pos = text.find(f"({ip2})")
last_space2 = text.rfind(' ', 0, ip2_pos)
country2 = text[last_space2+1:ip2_pos].strip()

print(f"Country1: {country1}, Country2: {country2}")

内容的提问来源于stack exchange,提问作者andrea.p

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:45:43