4

我正在尝试检查字符串是否以相同的单词开头和结尾。例如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

"earthearth", "eartheeearth", "地球地球火星" -->invalid

4

5 回答 5

7

请改用str.startswithandstr.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
于 2013-06-30T09:52:28.073 回答
4

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

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

仅当它匹配一个字符串时

  • 以相同的单词开头和结尾
  • 有一个词
于 2013-06-30T09:52:50.287 回答
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.splitand str.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
于 2013-06-30T09:52:16.993 回答
3

这里:

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

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

X[0] == X[-1]
于 2013-06-30T10:23:31.523 回答
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)检查您要查找的单词是否是“句子”中唯一的单词,或者该单词是否在句子中。

于 2013-06-30T10:08:34.603 回答