

No_match_was_found = ( match_output is None ) #match_output = re.search(raw_search_string, input_string, #As noted by if you want to ignore case, uncomment Match_output = re.search(raw_search_string, input_string) Raw_search_string = r"\b" + search_string + r"\b" # Create a raw string with word boundaries from the user's input_string # -*- coding: utf-8 find_only_whole_word.pyĭef find_only_whole_word(search_string, input_string): This can be accomplished by the following code: #!/usr/bin/env python3 # Use "ample", part of the word, "sample": (s)ample Here's a more complete sampling of the behavior to be expected. The useful answer from shows output, but not True or False. There is no output from the second command. We have a step towards that behavior with the answer from, but it's a little hard to interpret/implement. Once again, this is how I understand the OP's question. The following behavior should then be expected. Let's say the method which should exhibit the behavior I've discussed is named find_only_whole_word(search_string, input_string) > regex=re.compile(r"\bis\b") # For ignore case: re.compile(r"\bis\b", re.IGNORECASE) In other words, we need to generalize the (excellent) answer by using re.match(r"\bis\b", your_string) The same r"\bis\b" concept is also used in the answer by who started the generalizing discussion by showing > y="this isis a sample." The behavior of other search strings should be noted to understand the concept. I think that these answers are correct, but I think that there is more of the question's fundamental meaning that needs to be addressed. Only the word "is" has been used in examples up to this point. The other answers have the behavior of "don't return a word unless that word is found by itself - not inside of other words." The "word boundary" shorthand character class does this job nicely. I hope this helps clarify things as to why we use word boundaries. In this case, the reference is to the search token "is" as it is found in the word "is". and "is" should return True since there is no alpha character on the left and on the right side. If someone were to search the string, a for the word "hi", they should receive False as the response. Īs I understand, the reference is to the search token, "hi" as it is found in the word, "this". I want to match whole word - for example match "hi" should return False since "hi" is not a word. Perhaps I can illustrate what I mean by stating that I think that the OP used the examples used because of the following. The answers given do help illustrate the concept, and I think they are excellent. Specifically, the desired output of a boolean was not accomplished. I think that the behavior desired by the OP was not completely achieved using the answers given.
