Python正则表达式,获取实际返回

时间:2015-03-31 23:28:33

标签: python regex

我正在尝试对整个文件进行正则表达式,但是我最终会得到这样的列表:

NONE
NONE
NONE
NONE
<_sre.SRE_Match object at 0x7f89b0152db0>
NONE
<_sre.SRE_Match object at 0x7f89b0152db0>

如何获得实际线路?

这是我的代码:

 dictionaryFile = "file.txt"
 patternMatch = re.compile('^(\w{6,8})(\s+)(\d+)(\s+)(.+)(\s+)(\d{1,3}\s*-\s*\d{1,3})')

 with open(dictionaryFile) as file:
     for line in file:
          result = patternMatch.search(line)
          print result

以下是我正在申请的文件示例:

HETELAVL        2       IS THERE A TELEPHONE ELSEWHERE ON           35 - 36
                WHICH PEOPLE IN THIS HOUSEHOLD CAN 
                BE CONTACTED?

                EDITED UNIVERSE:    HETELHHD = 2

                VALID ENTRIES

                1   YES
                2   NO

 HEPHONEO       2       IS A TELEPHONE INTERVIEW ACCEPTABLE?            37 - 38

                EDITED UNIVERSE:    HETELHHD = 1 OR HETELAVL = 1

                VALID ENTRIES
                1   YES
                2   NO

我想回复一下:

HETELAVL        2       IS THERE A TELEPHONE ELSEWHERE ON           35 - 36
HEPHONEO        2       IS A TELEPHONE INTERVIEW ACCEPTABLE?            37 - 38

2 个答案:

答案 0 :(得分:1)

如果字符串中的位置与模式不匹配,则

search()会返回None

检查result是否不是None并打印line

result = patternMatch.search(line)
if result is not None:
    print line

答案 1 :(得分:0)

搜索返回一个匹配对象,所以不要只打印它,因为它会打印对象使用result.group(0)来获取实际的行。