简体   繁体   中英

get multiline data in parantheses without regex

I am trying to parse go metafiles in the format of following:

require (
    github.com/cheggaaa/pb v1.0.28
    github.com/coreos/go-semver v0.2.0 // indirect
    github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e // indirect
    github.com/dustin/go-humanize v1.0.0
    github.com/fatih/color v1.7.0
        ...
        )

how do I get data between brackets and without using a regexp? (otherwise this noobish question would not exist at all). I have tried playing with split() but failed so far.

@rdas's suggestion of [l.strip() for l in file.readlines()[1:-1]] will work if the metafile is formatted like your example is. But really, you should just use regex. It's easier.

You can read the entire contents, split it into separate lines, then slice off the first and last lines:

with open(metafile) as f:
    requirements = f.read().splitlines()[1:-1]

Using with to open a file ensures it is closed properly when the scope ends.

Here is a code that should do it. It will copy all the lines between 'requiere (' and ')' as long as there are no other ')' in those blocks.

data file:

random stuff
require (
    github.com/cheggaaa/pb v1.0.28
    github.com/coreos/go-semver v0.2.0 // indirect
    github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e //indirect
    github.com/dustin/go-humanize v1.0.0
    github.com/fatih/color v1.7.0
        ...
        )



random stuff

out file :

github.com/cheggaaa/pb v1.0.28
github.com/coreos/go-semver v0.2.0 // indirect
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e //indirect
github.com/dustin/go-humanize v1.0.0
github.com/fatih/color v1.7.0
    ...

code :

f = open('data', 'r')
f2 = open('out', 'w')

toggle = False

for line in f:
    if 'require (' in line:
        toggle = True
        continue
    if toggle:
        if ')' in line:
            toggle = False
        else:
            f2.write(line)

f.close()
f2.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM