我想转换以下内容:
"some text http://one.two.three.source.com more text. more text more text http://source.com more text. more text http://one.source.com more text more text. more text http://one.two.source.com more text more text"
为此:
"some text http://one_two_three.target.com more text more text more text http://target.com more text more text http://one.target.com more text more text more text http://one_two.target.com more text more text"
我想转换'.'在一大段文本中将每个子域分隔为“_”,问题是我想让它以是否有子域为条件。 我无法预测文本的其余部分,并且只需要对 url 模式进行转换。
这是我目前所拥有的:
src = 'source.com'
dst = 'target.com'
reMatch = r'http(?P<a>s?):(?P<b>\\?)/(?P<c>\\?)/(?P<d>([^.:/]+\.)?)(?P<e>([^.:/]+\.)?)(?P<f>([^.:/]+\.)?)' + src
p = re.compile(reMatch, re.IGNORECASE)
reReplace = r'http\g<a>:\g<b>/\g<c>/\g<d>\g<e>\g<f>' + dst
p.sub(reReplace, content)
它仅将“source.com”替换为“target.com”并复制子域(最多 3 个)但不替换“.”在子域之间使用“_”。
最佳答案
我构建了一个函数,根据您的输入实现您想要的输出:
def special_replace(s):
p=re.compile(r"(http://.*?)(\.?source\.com)")
spl=p.split(s)
newtext=[]
for text in spl:
if text.startswith("http://"):
text=text.replace(".","_")
elif text.endswith("source.com"):
text=text.replace("source.com", "target.com")
newtext.append(text)
return "".join(newtext)
它不是那么优雅,但它达到了你的目标:)。
关于Python 正则表达式如果组匹配则放置不同的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12286660/