j riot
j riot

Reputation: 544

Python Regex, Get Actual Line Back

I am trying to regex over an entire file, however I keep ending up with a list like this:

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

How do I get the actual line back?

Here is my code:

 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

Here is an example of the file I am regex'ing over:

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

I would like to get this back:

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

Upvotes: 0

Views: 40

Answers (2)

avinash pandey
avinash pandey

Reputation: 1381

search returns a match object so don't just print it as it will print the object use result.group(0) to get the actual line.

Upvotes: 0

alecxe
alecxe

Reputation: 473813

search() returns None if no position in the string matches the pattern.

Check if the result is not None and print line:

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

Upvotes: 1

Related Questions