可以使用Python的正则表达式模块re来实现。

首先定义一个正则表达式来匹配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或者域名我需要检测它是否为IP或者域名然后将域名或者IP里面的替换成 而不影响到文字

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

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