【问题标题】:Replace a substring between two substrings替换两个子串之间的子串
【发布时间】:2022-09-28 18:33:51
【问题描述】:

如何在下面提供的l 字符串中用222.6 替换page1/_type-A 之间的子字符串?

l = \'https://homepage.com/home/page1/222.6 a_type-A/go\'
replace_with = \'222.6\'

预期结果:

https://homepage.com/home/page1/222.6_type-A/go

我试过了:

import re
re.sub(\'page1/.*?_type-A\',\'\',l, flags=re.DOTALL)

但它也删除了page1/_type-A

  • 试试:re.sub(\'(?<=page1/).*?(?=_type-A)\', replace_with, l)

标签: python regex


【解决方案1】:

您可以使用

import re
l = 'https://'+'homepage.com/home/page1/222.6 a_type-A/go'
replace_with = '222.6'
print (re.sub('(page1/).*?(_type-A)',fr'\g<1>{replace_with}\2',l, flags=re.DOTALL))

输出:https://homepage.com/home/page1/222.6_type-A/go

Python demo online

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 2016-11-24
    相关资源
    最近更新 更多