在Python中仅替换域

在Python中仅替换域,python,regex,urlparse,Python,Regex,Urlparse,我一直在使用一个正则表达式来搜索文档中的所有URL并替换它们,但现在我只想替换主机名,而不是子域或URL的任何其他部分 例如,我想要> 这是我正在编写的一个工具,用于清理文档,对于其中的一些文档,我是相当陌生的。任何帮助都将不胜感激。谢谢 这是到目前为止我快速而肮脏的查找和替换: import fileinput import re for line in fileinput.input(): line = re.sub( r'^(?:http:\/\/|www\.|h

我一直在使用一个正则表达式来搜索文档中的所有URL并替换它们,但现在我只想替换主机名,而不是子域或URL的任何其他部分

例如,我想要>

这是我正在编写的一个工具,用于清理文档,对于其中的一些文档,我是相当陌生的。任何帮助都将不胜感激。谢谢

这是到目前为止我快速而肮脏的查找和替换:

import fileinput
import re

for line in fileinput.input():
    line = re.sub(
        r'^(?:http:\/\/|www\.|https:\/\/)([^\/]+)',
        r'client.com', line.rstrip())
    line = re.sub(
        r'\b(\d{1,3}\.){2}\d{1,3}\b',
        r'1.33.7', line.rstrip())
    print(line)

我意识到URL解析可以实现这一点,但我希望它能在文档中找到URL,我不想提供它们。也许我只是需要帮助,使用regex查找URL并将其传递给urlparse以删除我想要的部分。希望这能澄清问题。

我下面的解决方案将URL分为3组:主机前、主机名和主机后:

import re
regex = r"^(http[:\/\w\.]*[/.])(\w+)(\.[\w\/]+)$"

target = "http://olddomain.com"
print re.sub(regex,r"\1newdomain\3",target)
# 'http://newdomain.com'

target = "http://ftp.olddomain.com"
print re.sub(regex,r"\1newdomain\3",target)
# 'http://ftp.newdomain.com'

target = "https://sub.sub.olddomain.com/sub/sub"
print re.sub(regex,r"\1newdomain\3",target)
# 'https://sub.sub.newdomain.com/sub/sub'

target = "how.about.this"
print re.sub(regex,r"\1newdomain\3",target)
# 'how.about.this'

我下面的解决方案将URL分为3组:主机前、主机名和主机后:

import re
regex = r"^(http[:\/\w\.]*[/.])(\w+)(\.[\w\/]+)$"

target = "http://olddomain.com"
print re.sub(regex,r"\1newdomain\3",target)
# 'http://newdomain.com'

target = "http://ftp.olddomain.com"
print re.sub(regex,r"\1newdomain\3",target)
# 'http://ftp.newdomain.com'

target = "https://sub.sub.olddomain.com/sub/sub"
print re.sub(regex,r"\1newdomain\3",target)
# 'https://sub.sub.newdomain.com/sub/sub'

target = "how.about.this"
print re.sub(regex,r"\1newdomain\3",target)
# 'how.about.this'
删除注释并注释掉文件输入时给出。我把它放在这里了,所以它可以按要求工作

python /tmp/test2.py
http://newdomain.com/test/test
this urel http://www.newdomain.com/test/test dends
删除注释并注释掉文件输入时给出。我把它放在这里了,所以它可以按要求工作

python /tmp/test2.py
http://newdomain.com/test/test
this urel http://www.newdomain.com/test/test dends

此问题与的可能重复相同我不想指定url,我想搜索文档中的所有url并替换域。此问题与的可能重复相同我不想指定url,我想搜索文档中的所有url并替换域。