Sara Stenhouse
Sara Stenhouse

Reputation: 1

Using Regex to return only the first occurence of a string in a file

I have a file that contains these values:

162.0000
162.2000
162.4000
162.6000
162.8000
162.0000
162.2000
162.4000
162.6000
162.8000

But i only want to print these values:

162.0000
162.2000
162.4000
162.6000
162.8000

This is my current code:

pattern=re.compile(r'(1[6][2]\.[0-9][0]+)')
if pattern.search(line):
    print line

Is there a way I can show only the first occurrence of each of these numbers? Thanks!

Upvotes: 0

Views: 27

Answers (1)

javidcf
javidcf

Reputation: 59741

Regular expressions alone cannot solve the problem, use a set to keep track of what you have already seen:

pattern=re.compile(r'(1[6][2]\.[0-9][0]+)')
seen = set()
if pattern.search(line):
    if line not in seen:
        seen.add(line)
        print line

Upvotes: 2

Related Questions