Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find whether the string starts and ends with the same word

Tags:

python

regex

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

like image 281
Ajax Avatar asked Dec 01 '22 19:12

Ajax


2 Answers

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
like image 178
Volatility Avatar answered Dec 20 '22 17:12

Volatility


You can use backreference within regex

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

This would match a string only if it

  • starts and ends with the same word
  • has a single word
like image 34
Anirudha Avatar answered Dec 20 '22 17:12

Anirudha