简体   繁体   中英

read a multiline string in python

I need to parse a string and read a particular substring from it. The string I need to parse is as follows :

domain
(
    (device
          (console
               (xxxxxx)
               (XXXXXX)
          )
    )
)

domain
(
    (device
          (vfb
               (xxxxxx)
               (location : 5903)
          )
    )
)

This is just a sample string. The actual string might contain many such substrings. I need to get the value of location field just from the "vfb" substring. I tried the findall and search functions as follows

import re
text=re.search('(device(vfb(.*?)))',stringname)

and

import re
text=re.findall('(device(vfb(.*?)))',stringname,re.DOTALL)

But I am getting empty string always. Is there a easy way to do this ? Thanks

Why don't you just look for location key-value pair?

>>> re.findall(r'(\w+) : (\w+)', s)
    [('location', '5903')]

Simple python script:

fp = open("input.txt", "r")

data = fp.readlines()
for line in data:

    if "location" in line:
        print line.split(":")[1].split(")")[0].strip()

fp.close()
re.findall(r'device.*?\(vfb.*\(.*\).*(\(.*?\))', s, re.DOTALL)

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