【问题标题】:How to search for a word (exact match) within a string?如何在字符串中搜索单词(完全匹配)?
【发布时间】:2011-11-30 07:18:01
【问题描述】:

我正在尝试子串搜索

>>>str1 = 'this'
>>>str2 = 'researching this'
>>>str3 = 'researching this '

>>>"[^a-z]"+str1+"[^a-z]" in str2
False

>>>"[^a-z]"+str1+"[^a-z]" in str3
False

我想在 str3 中查找时为 True。我做错了什么?

【问题讨论】:

    标签: python string search


    【解决方案1】:

    你想要 Python 的 re 模块:

    >>> import re
    >>> regex = re.compile(r"\sthis\s") # \s is whitespace
    >>> # OR
    >>> regex = re.compile(r"\Wthis\W")
    >>> # \w is a word character ([a-zA-Z0-9_]), \W is anything but a word character
    >>> str2 = 'researching this'
    >>> str3 = 'researching this '
    >>> bool(regex.search(str2))
    False
    >>> regex.search(str3)
    <_sre.SRE_Match object at 0x10044e8b8>
    >>> bool(regex.search(str3))
    True
    

    我有一种预感,您实际上是在寻找“this”这个词,而不是围绕它的非单词字符的“this”。在这种情况下,您应该使用单词边界转义序列\b。

    【讨论】:

      【解决方案2】:

      看起来您想使用正则表达式,但您使用的是普通字符串方法。你需要使用re module中的方法:

      import re
      >>> re.search("[^a-z]"+str1+"[^a-z]", str2)
      >>> re.search("[^a-z]"+str1+"[^a-z]", str3)
      <_sre.SRE_Match object at 0x0000000006C69370>
      

      【讨论】:

      • 谢谢。如果我想使用re.search("[^a-z]"+'researching'+"[^a-z]", str3) 搜索“研究”,我没有得到任何对象值。我做错了什么?
      • @Pradeep 请参阅我的回答中提到\b 的部分。
      【解决方案3】:

      对于 Python 中的正则表达式,请使用 re 模块:

      >>> import re
      >>> re.search("[^a-z]"+str1+"[^a-z]", str2) is not None
      False
      >>> re.search("[^a-z]"+str1+"[^a-z]", str3) is not None
      True
      

      【讨论】:

        【解决方案4】:
        import re
        str1 = 'this'
        str2 = 'researching this'
        str3 = 'researching this '
        
        if re.search("[^a-z]"+str1+"[^a-z]", str2):
            print "found!"
        
        if re.search("[^a-z]"+str1+"[^a-z]", str3):
            print "found!"
        

        【讨论】:

          【解决方案5】:

          我认为in 不会进行正则表达式搜索。

          看看re 模块。

          目前尚不清楚您实际上要做什么,但是如果您想知道“this”是否在“researching this”中,请执行以下操作:

          "this" in "researching this"
          

          (或)

          str1 in str3
          

          或者,如果您只想找到整个单词,请执行以下操作:

          "this" in "researching this".split()
          

          结果是它将“researching this”拆分为["researching", "this"],然后检查其中的确切单词“this”。所以,这是错误的:

          "this" in "researching thistles".split()
          

          【讨论】:

          • 我认为这个想法是考虑单词边界以确保找到精确匹配(例如,str1 in "researching thistles" 应该返回 False)。
          【解决方案6】:

          使用re 模块。 re 模块是您应该使用的模块。 re岩石。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-07-25
            • 2020-06-23
            • 1970-01-01
            • 1970-01-01
            • 2020-12-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多