繁体   English   中英

在python中使用regex在字符串中的子字符串前添加空格

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM