Jobias Jobias - 2 months ago 5
Python Question

Python Regular expression start on specific line

I use Regex to read a text file, but I want the regex to start from a specific line, how do I do that?
Text file example:

ST
** L57.nc1
BS15-0124
L57
L57
L57
S355JR
1
L150/15
L
2700.00,2700.00
150.00
150.00
15.00
15.00
16.00
34.420
0.600
0.000
0.000
0.000
0.000


Currently I'm using a very long regex that matches every line but it is very very slow. If for example I want to capture 12th line can I do something like from line(11) use this regex?

Is there a start from line number option?

Cheers,
Job

Answer

As we don't know how you read and parse the file, i have to guess.

Try something like that:

with open("test.txt", "r") as f:
    lines = f.readlines()

    # Check only from 12 to 14
    to_check = "".join(lines[11:14])

    print to_check
    # Result:
    #  150.00
    #  150.00
    #   15.00

    # Example call
    re.match("your nice regexp", to_check)

Using this, you get a small chunk of your file you can use your regex on.

Comments