While parsing an ASCII file, I want to perform some operations on a section of lines.
The length of the section will vary, so I made a while loop that should continue until I reach a line starting with "A", indicating that the section has ended. However, within the section there will be some lines starting with "AB", which I want to include.
So I'm looking for something like: while not line[0] == "A", unless line[:2] == "AB"
I.e. "AA", "AC", "A$" or "A-whatever" should break the loop, but "AB" should not.
I'm a novice and haven't found the right search terms for a nice clean solution to this, though I'm sure one must exist, or do I need to resort to regex?
Edit: As requested here is a sample:
*SIGNAL* $$$1 2 -2 ;
R1.2 U1.36
3.1 3.635 0 0.3048 1792 THERMAL
14.92 14 65 0.3048 1792 THERMAL
*SIGNAL* $$$2 2 -2 ;
R1.1 U1.40
3.1 2.365 0 0.3048 1792 THERMAL
18.984 14 65 0.3048 1792 THERMAL
*SIGNAL* $$$3 2 -2 ;
U1.16 U1.22
24.064 26.7 0 0.3048 1792 THERMAL
18 29.2 1 0.3048 1280 STANDARDVIA THERMAL TEARDROP N 90 90
17.968 29.168 1 0.3048 1536
17.968 26.7 65 0.3048 768 THERMAL TEARDROP P 90 90
U1.16 R3.2
24.064 26.7 1 0.3048 1280 THERMAL TEARDROP N 90 90
29 26.7 1 0.3048 1536
29.7 26 1 0.3048 1536
33.4 26 1 0.3048 1536
33.4 26.035 65 0.3048 768 THERMAL TEARDROP P 90 90
U1.22 U1.2
17.968 26.7 0 0.3048 1792 THERMAL
21.016 14 65 0.3048 1792 THERMAL
U1.26 U1.22
13.142 24.922 0 0.3048 1792 THERMAL
17.968 26.7 65 0.3048 1792 THERMAL
R2.2 U1.2
17 3.65 0 0.3048 1792 THERMAL
21.016 14 65 0.3048 1792 THERMAL
*SIGNAL* $$$4 2 -2 ;
R2.1 U1.4
17 2.35 0 0.3048 1792 THERMAL
23.048 14 65 0.3048 1792 THERMAL
*SIGNAL* $$$5 2 -2 ;
R3.1 U1.6
33.4 24.765 0 0.3048 1792 THERMAL
25.842 15.778 65 0.3048 1792 THERMAL
*TESTPOINT*
...
In this case, the next section is called "TESTPOINT", but that will vary. The only known character is the beginning "*", so unfortunately that includes all the "SIGNAL"-lines as well.
This would be perfect for a regular expression.
For example,
^A(?!B).*
will match a line that starts with A and does not have a B afterwards.
You could probably match entire sections this way, for example (assuming that you want to match everything from Z to A (unless AB), then
(?s)^Z.*?^A(?!B)
would match that. If you can specify your problem more precisely, it's possible to design a more specific regex.
You may want to use "or"
while line[0] != "A" or line[:2] == "AB":
# your code here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With