Python 替换文本中的 IP 和域名点号为 [.]
您可以使用正则表达式来匹配并替换 IP 或者域名中的点号。下面是一个示例代码:
import re
text = 'This is a sample text with an IP address 192.168.1.1 and a domain name www.example.com'
# Define regular expression pattern for IP address and domain name
ip_pattern = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
domain_pattern = r'[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+'
# Replace dots in IP address with [.] and dots in domain name with [.]
text = re.sub(ip_pattern, lambda match: match.group(0).replace('.', '[.]'), text)
text = re.sub(domain_pattern, lambda match: match.group(0).replace('.', '[.]'), text)
print(text)
输出结果:
This is a sample text with an IP address 192[.]168.1.1] and a domain name www[.]example[.]com
这个代码首先定义了两个正则表达式,一个用于匹配 IP 地址,另一个用于匹配域名。然后,使用 re.sub() 函数对文本进行替换。re.sub() 函数可以接受一个函数作为替换参数,这个函数可以根据匹配结果进行替换操作。在这个示例中,我们使用 lambda 函数来将点号替换为 [.]。
原文地址: https://www.cveoy.top/t/topic/ovq9 著作权归作者所有。请勿转载和采集!