好吧,如果你绝对想要正则表达式,你可以使用环视,因为它们不消耗字符。
>>>import re
>>>s1 = 'earth is earth'
>>>s2 = 'earth'
>>>m = re.search(r"^(?=(earth)).*(earth)$",s1)
>>>m.group(1)
'earth'
>>>m.group(2)
'earth'
>>>m = re.search(r"^(?=(earth)).*(earth)$",s2)
>>>m.group(1)
'earth'
>>>m.group(2)
'earth'
对于任何字符串,您也许可以使用这个:
^(?=([A-Za-z]+)).*(\1)$
我假设单词只是字母字符。如果您的意思是非空格字符中的单词,那么您可以使用\S
而不是[A-Za-z]
.
编辑:好的,似乎还有更多。我认为可能适合的是:
^(?=(earth\b)).*((?:^|\s)\1)$
对于工作地球。对于存储在名为word
;的变量中的任何单词
>>> word = 'earth' # Makes it so you can change it anytime
>>> pattern = re.compile('^(?=(' + word + '\b)).*((?:^|\s)\1)$')
>>> m.search(pattern, s)
接受:
earth is earth
earth
拒绝:
earthearth
eartheearth
earthis earth
然后提取捕获的组或检查组是否为空。
我添加的部分是(?:^|\s)
检查您要查找的单词是否是“句子”中唯一的单词,或者该单词是否在句子中。