首页 > 解决方案 > 如果它包含python中的某些字符,如何删除完整的单词

问题描述

如果单词开始或包含某些字符,我想删除句子中的单词。

前任:

string_s = '( active parts ) acetylene cas89343-06-6'

如果单词包含或以 cas 开头,则从字符串中删除整个单词

input1 =  '( active parts ) acetylene cas89343-06-6'
output1 = '( active parts ) acetylene'

input2 = '( active parts ) acetylene th.cas1345'
output2 = '( active parts ) acetylene'

标签: python

解决方案


re.sub与 pattern 一起使用\b[\w-]*cas[\w-]*\b,并用一个空格替换,然后修剪输出:

string_s = '( active parts ) acetylene cas89343-06-6'
output = re.sub(r'\b[\w-]*cas[\w-]*\b', ' ', string_s).strip()
print(string_s + '\n' + output)

这打印:

( active parts ) acetylene cas89343-06-6
( active parts ) acetylene

推荐阅读