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

时间:2013-06-30 09:49:54

标签: python regex

我正在尝试检查字符串是否以相同的单词开头和结尾。例如,earth

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

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

目前我已经通过

对此案进行了硬编码
if m is not None or s=='earth':
    print "found"

还有其他办法吗?

编辑:

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

some examples

“地球是地球”,“地球”, - > valid

invalid

5 个答案:

答案 0 :(得分:7)

请改用str.startswithstr.endswith方法。

>>> 'earth'.startswith('earth')
True
>>> 'earth'.endswith('earth')
True

您可以简单地将它们组合成一个功能:

def startsandendswith(main_str):
    return main_str.startswith(check_str) and main_str.endswith(check_str)

现在我们可以称之为:

>>> startsandendswith('earth', 'earth')
True

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

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

运行它:

>>> startsandendswith('earth', 'earth')
True
>>> startsandendswith('earth is earth', 'earth')
True
>>> startsandendswith('earthis earth', 'earth')
False

答案 1 :(得分:4)

您可以在正则表达式中使用反向引用

^(\w+\b)(.*\b\1$|$)

仅当字符串

时才匹配
  • 相同
  • 开头和结尾
  • 只有一个单词

答案 2 :(得分:3)

您可以使用str.startswithstr.endswith

>>> strs = "earthfooearth"
>>> strs.startswith('earth') and strs.endswith("earth")
True
>>> strs = "earth"
>>> strs.startswith('earth') and strs.endswith("earth")
True

<强>更新

如果单词以空格分隔,并且不知道开始和结束字符串,则使用str.splitstr.rsplit

>>> strs = "foo bar foo"
>>> strs.split(None, 1)[0] == strs.rsplit(None, 1)[-1]
True
# single word
>>> strs = "foo"
>>> strs.split(None, 1)[0] == strs.rsplit(None, 1)[-1]
True
>>> strs = "foo bar ffoo"
>>> strs.split(None, 1)[0] == strs.rsplit(None, 1)[-1]
False

答案 3 :(得分:3)

下面:

X = words.split()
X[:1] == X[-1:]

切片使它也适用于空字符串,并且可以很好地扩展到任意数量的单词。如果words不能为空,请使用

X[0] == X[-1]

答案 4 :(得分:1)

好吧,如果你绝对想要正则表达式,你可以使用外观,因为它们不会消耗字符。

>>>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),它会检查您要查找的单词是否是“句子”中唯一的单词,或者单词是否在句子中。

相关问题