Well, if you absolutely want a regular expression, you can use lookarounds, since they don't consume characters.
>>>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'
For any line, you can use this:
^(?=([A-Za-z]+)).*(\1)$
I assume that the words are only symbols of the alphabet. If you mean words as characters without spaces, you can go instead of \S instead of [A-Za-z] .
EDIT: Okay, it looks like he is bigger. I think this may come up:
^(?=(earth\b)).*((?:^|\s)\1)$
For working land. For any word stored in a variable named word ;
>>> word = 'earth'
Accepts:
earth is earth earth
Deviation:
earthearth eartheearth earthis earth
And after that, remove the captured groups or check if the group is empty or not.
Added bit: (?:^|\s) , which checks if the word you are looking for is the only one in the "sentence" or the word in the sentence.
Jerry source share