tekken
tekken

Reputation: 43

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

Upvotes: 0

Views: 990

Answers (3)

09dzxue
09dzxue

Reputation: 27

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

Upvotes: 0

ATOzTOA
ATOzTOA

Reputation: 35950

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()

Upvotes: 0

Blender
Blender

Reputation: 298196

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

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

Upvotes: 1

Related Questions