【问题标题】:Python, regular expression search matchobj triggers errorPython,正则表达式搜索matchobj触发错误
【发布时间】:2012-01-12 16:17:13
【问题描述】:

不知何故,我知道这个问题的答案是显而易见的,但我花了几天时间试图找出为什么我似乎无法找到 reg.exp,但没有成功。下面脚本中的 mach 对象。 这是我收到的错误消息:

    subject:     Re: Why DOJ BMFEA Baton Rouge rejected Gonzalaz Pen Code 99999 death case


xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Traceback (most recent call last):
  File "C:\Apps\UtilitiesByMarc\test_search4Sender_aaB.py", line 46, in <module>
    print fn_cull_sender_info(date_string_raw)
  File "C:\Apps\UtilitiesByMarc\test_search4Sender_aaB.py", line 35, in fn_cull_sender_info
    print 'Line 35:  matchObj found\n str(match_obj.group(0)) = ' +  str(match_obj.group(0))
NameError: global name 'match_obj' is not defined

以下是代码:

import sys
import re, pdb
#pdb.set_trace()

def fn_get_srctxt_hg_datestring_rawdata_from_clipbd(): 
    this_scriptz_FULLName = sys.argv[0]
    try:
        date_string_raw = sys.argv[1]
        return returnval    
    except:
        date_string_raw = ''

        import win32clipboard

        win32clipboard.OpenClipboard()
        clip_text = win32clipboard.GetClipboardData()
        win32clipboard.CloseClipboard()    

        date_string_raw = clip_text
        returnval = clip_text
        return returnval    




def fn_cull_sender_info(date_string_raw): # 
    # Do re replacements
    import re
    sender_info = 'Line 29 empty'
    print '\n\nLine 30:  date_string_raw = [starts on next line...]\n' + str(date_string_raw) + '\n' + 'x'*80 + '\n'
    srchpatrn = r"(from:\t )(([A-Za-z\. ]+?)(?: ))?([A-Za-z.\-_0-9]+@[A-Za-z.\-_0-9].+?\.(?:com|org|net))"        

    matchObj = re.search(srchpatrn, date_string_raw)
    if matchObj:
        print 'Line 35:  matchObj found\n str(match_obj.group(0)) = ' +  str(match_obj.group(0))
        sender_info = str(match_obj.group(0))
    return sender_info


if __name__ == '__main__': 
    harvey = fn_get_srctxt_hg_datestring_rawdata_from_clipbd()
    print harvey
    date_string_raw = harvey
    print '*****'*50
    print '\n\n'
    print fn_cull_sender_info(date_string_raw)

以下(由另一个函数生成的文本[此处未显示])是我在运行上面的 python 代码时在 Windows 剪贴板中的文本:

sender_display_name = matchObj.search(date_string_raw).group(2)#.strip() 
sender_eml =      matchObj.search(date_string_raw).group(4)

我花了几天时间试图找出我做错了什么。 我想将正则表达式组 3 和 4 捕获到字符串变量中,例如

但由于我无法让 matchObj 返回 True,所以我无法到达那里。

【问题讨论】:

    标签: python regex search regex-group


    【解决方案1】:

    您之前定义了matchObj,而不是match_obj

    【讨论】:

    • 这种问题很容易用pyflakes这样的语法检查工具检测出来。
    • 我用pylint,很直接。
    猜你喜欢
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2015-02-23
    • 2015-05-30
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多