I am trying to check whether the string starts and ends with the same word. egearth. 
s=raw_input();
m=re.search(r"^(earth).*(earth)$",s)
if m is not None:
    print "found"
my problem is when the string consists only of one word eg: earth
At present I have hard coded this case by
if m is not None or s=='earth':
    print "found"
Is there any other way to do this?
EDIT:
words in a string are separated by spaces. looking for a regex solution
some examples: 
"earth is earth" ,"earth", --> valid
"earthearth", "eartheeearth", "earth earth mars" --> invalid
Use the str.startswith and str.endswith methods instead.
>>> 'earth'.startswith('earth')
True
>>> 'earth'.endswith('earth')
True
You can simply combine them into a single function:
def startsandendswith(main_str):
    return main_str.startswith(check_str) and main_str.endswith(check_str)
And now we can call it:
>>> startsandendswith('earth', 'earth')
True
If, however, if the code matches words and not part of a word, it might be simpler to split the string, and then check if the first and last word are the string you want to check for:
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
Running it:
>>> startsandendswith('earth', 'earth')
True
>>> startsandendswith('earth is earth', 'earth')
True
>>> startsandendswith('earthis earth', 'earth')
False
You can use backreference within regex
^(\w+\b)(.*\b\1$|$)
This would match a string only if it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With