[英]How to replace substring between two other substrings in python?
[英]Replace a substring between two substrings
如何在下面提供的l
字符串中用222.6
替換page1/
和_type-A
之間的 substring?
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
。
您可以使用
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))
Output: https://homepage.com/home/page1/222.6_type-A/go
請注意,您使用空字符串作為替換參數。 在上面的代碼片段中, .*?
之前和之后的部分被捕獲並且\g<1>
指的是第一組值,而\2
指的是替換模式中的第二組值。 明確的反向引用形式 ( \g<X>
) 用於避免反向引用問題,因為在反向引用之后有一個數字。
由於替換模式不包含反斜杠,因此無需預處理(轉義)其中的任何內容。
你可以像這樣使用re.sub
:
import re
l = 'https://homepage.com/home/page1/222.6 a_type-A/go'
replace_with = '222.6'
print (re.sub(r'(?<=page1/).*?(?=_type-A)', replace_with, l))
Output:
https://homepage.com/home/page1/222.6_type-A/go
正則表達式分解:
(?<=page1/)
:回溯斷言我們在之前的 position 處有page1/
.*?
: 匹配任意字符串的 0 個或多個(惰性)(?=_type-A)
:先行斷言我們在下一個 position 有_type-A
這有效:
import re
l = 'https://homepage.com/home/page1/222.6 a_type-A/go'
pattern = r"(?<=page1/).*?(?=_type)"
replace_with = '222.6'
s = re.sub(pattern, replace_with, l)
print(s)
該模式使用積極的前瞻和回顧斷言, ?<=
和?=
。 僅當字符串在模式中的斷言前后出現但不使用它們時才會發生匹配。 這意味着re.sub
會查找前面帶有page1/
和后面帶有_type
的字符串,但只會替換中間的部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.