使用Python的正则表达式模块're'可以轻松实现检测文本中的IP地址和域名,并将其中的点号替换为方括号,而不影响其他文本内容。

首先定义一个正则表达式来匹配IP地址和域名:

import re

text = 'This is an example text with IP address 192.168.0.1 and domain name www.example.com'
pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b|\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}\b'
matches = re.findall(pattern, text)

print(matches)

输出结果为:

['192.168.0.1', 'www.example.com']

然后使用'replace'方法将字符串中的点号替换成方括号:

for match in matches:
    text = text.replace(match, match.replace('.', '[.]'))

print(text)

输出结果为:

This is an example text with IP address 192[.]168[.]0[.]1 and domain name www[.]example[.]com

完整代码如下:

import re

text = 'This is an example text with IP address 192.168.0.1 and domain name www.example.com'
pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b|\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}\b'
matches = re.findall(pattern, text)

for match in matches:
    text = text.replace(match, match.replace('.', '[.]'))

print(text)
Python 替换文本中的IP地址和域名点号为方括号

原文地址: https://www.cveoy.top/t/topic/ovrl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录