[英]How to add space before and after specific character using regex in Python?
[英]Add space before a substring in a string using regex in python
我有兩個清單:
list_1 = ["TP", "MP"]
list_2 = ["This is ABC12378TP0892S3", "This is XYZ12378MP0892S3"]
我想從list_1
獲取元素並搜索list_2
字符串。 如果找到了(例如TP
位於list_2
的第一個字符串中, MP
出現在list_2
的第二個字符串中),請刪除TP, MP
等右側的內容TP, MP
並在其左側插入空格。
我用re
嘗試了以下內容,但它只刪除了正確的部分:
[ re.sub(r'(' + '|'.join(list_1) + ')\d+', r'\1', string) for string in list_2 ]
您可以如下編譯正則表達式,然后使用它對每個列表條目執行sub()
:
import re
list_1 = ["TP", "MP"]
list_2 = ["This is ABC12378TP0892S3", "This is XYZ12378MP0892S3", "SDTP This is ABC12378TP0892S3"]
re_sub = re.compile(r'(.*\b\w+)({}).*'.format('|'.join(list_1))).sub
list_2 = [re_sub(r'\1 \2', t) for t in list_2]
print list_2
這將顯示:
['This is ABC12378 TP', 'This is XYZ12378 MP', 'SDTP This is ABC12378 TP']
在此示例中,正在使用的搜索模式是:
(.*\b\w+)(TP|MP).*
我想你很親密。 添加空格... r' \\1'
也不確定\\d+
,因此將其替換為.*
>>> [ re.sub(r'(' + '|'.join(list_1) + ').*', r' \1', string) for string in list_2 ]
['This is ABC12378 TP', 'This is XYZ12378 MP']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.