这是问题here的扩展
现在和链接的问题一样,答案使用space?
作为正则表达式模式来匹配字符串中有空格或没有空格。你知道吗
问题陈述:
我有一个字符串和一组短语。你知道吗
input_string = 'alice is a character from a fairy tale that lived in a wonder land. A character about whome no-one knows much about'
phrases_to_remove = ['wonderland', 'character', 'noone']
现在我要做的是从input_string
中删除数组phrases_to_remove
中最后出现的单词。你知道吗
output_string = 'alice is a character from a fairy tale that lived in a. A about whome knows much about'
注意:要删除的单词可能出现在字符串中,也可能不出现在字符串中,如果出现,它们可能以相同的形式出现{wonderland'或'character'、'noone'},也可能在单词之间带有空格或连字符(-),例如wonderland,no-one,character。你知道吗
代码的问题是,我无法删除space
或-
不匹配的单词。例如wonder land
和wonderland
和wonder-land
。你知道吗
我尝试将(-)?|( )?
作为正则表达式,但无法使其工作。你知道吗
我需要帮助
您可以一次使用一个:
对于空间:
对于“-”:
正则表达式的问题是分组。使用
(-)?|( )?
作为分隔符并不像您认为的那样。你知道吗考虑当单词列表为
a,b
时会发生什么:您希望这个正则表达式匹配
ab
或a b
或a-b
,但显然它没有这样做。它匹配a
、a-
、b
或<space>b
!你知道吗要解决这个问题,可以将分隔符括在它自己的组中:
([- ])?
。你知道吗如果您还想匹配像
wonder - land
(即在连字符之前/之后有空格的地方)这样的词,您应该使用下面的(\s*-?\s*)?
。你知道吗因为您不知道分隔符在哪里,所以可以生成一个由或regex组成的regex(使用单词边界来避免匹配子单词)。你知道吗
这些正则表达式将在每个字符上使用
str.join
替换单词的字母和[\s\-]*
(将零与“space”或“dash”的多个匹配)现在来处理“替换除第一个匹配项以外的所有项”部分:让我们定义一个对象,该对象将替换除第一个匹配项以外的所有项(使用内部计数器)
现在将
replace
方法传递给re.sub
:结果:
(生成的正则表达式非常复杂,顺便说一句:
\bw[\s\-]*o[\s\-]*n[\s\-]*d[\s\-]*e[\s\-]*r[\s\-]*l[\s\-]*a[\s\-]*n[\s\-]*d\b|\bc[\s\-]*h[\s\-]*a[\s\-]*r[\s\-]*a[\s\-]*c[\s\-]*t[\s\-]*e[\s\-]*r\b|\bn[\s\-]*o[\s\-]*o[\s\-]*n[\s\-]*e\b
)相关问题 更多 >
编程相关推荐