Python 如何使用正则表达式删除字符串中出现在单词两侧的各种标记?

Python 如何使用正则表达式删除字符串中出现在单词两侧的各种标记?,python,regex,Python,Regex,说 strng= 'I have to get to the <Color:D010644> maroon <Color:D010644> building before noon' 使这一点变得棘手的是,标记中的数字在行之间发生变化,并且数字的数量也不同。因此,在上面的示例中,数字是“D010644”,但在另一行中可能是“JJD93JD93J999333” 所以我需要正则表达式操作对所有的变化都是通用的 但是,标记名(在上面的示例中为“Color”)保持不变 您可以使

strng= 'I have to get to the <Color:D010644> maroon <Color:D010644> building before noon'
使这一点变得棘手的是,标记中的数字在行之间发生变化,并且数字的数量也不同。因此,在上面的示例中,数字是“D010644”,但在另一行中可能是“JJD93JD93J999333”

所以我需要正则表达式操作对所有的变化都是通用的


但是,标记名(在上面的示例中为“Color”)保持不变

您可以使用正则表达式过滤掉标记:

import re

text = 'I have to get to the <Color:D010644> maroon <Color:D010644> building before noon'

result = re.sub(r'(<Color:)\w+(> )', '', text)

print(result)  # I have to get to the maroon building before noon
重新导入
text='我必须在中午前到达栗色大楼'
结果=re.sub(r'()','',文本)
打印(结果)#我必须在中午前赶到栗色大楼

您也可以使用标准库执行此操作:

str = 'I have to get to the <Color:D010644> maroon <Color:D010644> building before noon'
new_string = ' '.join([elem for elem in str.split(' ') if not elem.startswith('<Color')])
print(new_string)

>>> I have to get to the maroon building before noon
str='我必须在中午前到达褐红色的大楼'
new_string=''.join([elem for elem in str.split('')if not elem.startswith('您解决问题的方法是编写一些代码。如果尽管您尽了最大的努力和调试尝试,但该代码仍然无法工作,请在此处将其编辑到您的问题中并寻求帮助,但不能没有这些先决条件。
str = 'I have to get to the <Color:D010644> maroon <Color:D010644> building before noon'
new_string = ' '.join([elem for elem in str.split(' ') if not elem.startswith('<Color')])
print(new_string)

>>> I have to get to the maroon building before noon