Find substring in string but only if whole words?

前端 未结 7 766
囚心锁ツ
囚心锁ツ 2020-11-27 07:32

What is an elegant way to look for a string within another string in Python, but only if the substring is within whole words, not part of a word?

Perhaps an example

7条回答
  •  囚心锁ツ
    2020-11-27 08:14

    I'm building off this answer.

    The problem with the above code is that it will return false when there are multiple occurrences of needle in haystack, with the second occurrence satisfying the search criteria but not the first.

    Here's my version:

    def find_substring(needle, haystack):
      search_start = 0
      while (search_start < len(haystack)):
        index = haystack.find(needle, search_start)
        if index == -1:
          return False
        is_prefix_whitespace = (index == 0 or haystack[index-1] in string.whitespace)
        search_start = index + len(needle)
        is_suffix_whitespace = (search_start == len(haystack) or haystack[search_start] in string.whitespace)
        if (is_prefix_whitespace and is_suffix_whitespace):
          return True
      return False
    

    Hope that helps!

提交回复
热议问题