查找字符串是否以相同的单词开头和结尾

Aja*_*jax 4 python regex

我试图检查字符串是否以相同的单词开头和结尾.例如earth.

s=raw_input();
m=re.search(r"^(earth).*(earth)$",s)
if m is not None:
    print "found"
Run Code Online (Sandbox Code Playgroud)

我的问题是当字符串只包含一个单词时,例如:earth

目前我已经硬编码了这个案例

if m is not None or s=='earth':
    print "found"
Run Code Online (Sandbox Code Playgroud)

有没有其他方法可以做到这一点?

编辑:

字符串中的单词用空格分隔.寻找正则表达式解决方案

some examples:

"地球是地球","地球", - > valid

"earthearth","eartheeearth","earth earth mars" - > invalid

Vol*_*ity 7

请改用str.startswithand str.endswith方法.

>>> 'earth'.startswith('earth')
True
>>> 'earth'.endswith('earth')
True
Run Code Online (Sandbox Code Playgroud)

您可以简单地将它们组合成一个函数:

def startsandendswith(main_str):
    return main_str.startswith(check_str) and main_str.endswith(check_str)
Run Code Online (Sandbox Code Playgroud)

现在我们可以称之为:

>>> startsandendswith('earth', 'earth')
True
Run Code Online (Sandbox Code Playgroud)

但是,如果代码匹配单词而不是单词的一部分,则拆分字符串可能更简单,然后检查第一个和最后一个单词是否是您要检查的字符串:

def startsandendswith(main_str, check_str):
    if not main_str:  # guard against empty strings
        return False
    words = main_str.split(' ')  # use main_str.split() to split on any whitespace
    return words[0] == words[-1] == check_str
Run Code Online (Sandbox Code Playgroud)

运行它:

>>> startsandendswith('earth', 'earth')
True
>>> startsandendswith('earth is earth', 'earth')
True
>>> startsandendswith('earthis earth', 'earth')
False
Run Code Online (Sandbox Code Playgroud)