views:

79

answers:

3

I would like to parse this Gstring with groovy :

Format type : Key, Value.

   def txt = """ <Lane_Attributes>
                  ID,1
                  FovCount,600
                  FovCounted,598
                  ...
                  </Lane_Attributes> """

And get a map like :

Map = [ID:1, FovCount:600, FovCounted:598]

How can I :
- extract text between tag and ?,
- and convert to a map ?

+3  A: 

Try this:

def map = [:]
txt.replaceAll('<.+>', '').trim().eachLine { line ->
   def parts = line.split(',')
   map[parts[0].trim()] = parts[1].trim().toInteger()
}
Burt Beckwith
In my txt file, I have several tags (ex : <Lane_Attributes>, but also <Code_Summary>). I try : def regex = "<$tag>(.*?)</$tag>", but does not work ? Any idea ? Thanks.
Fabien Barbier
+2  A: 
   def txt = """ <Lane_Attributes>
                  ID,1
                  FovCount,600
                  FovCounted,598

                  </Lane_Attributes> """

def map = new HashMap()
def lane = new XmlParser().parseText(txt)

 def content =  lane.text()


content.eachLine {
 line -> 

def dual =  line.split(',')
def key = dual[0].trim()
def val = dual[1].trim() 
//println "key: ${key} value: ${val}"
map.put(key,val)

}

println "map contains " +  map.inspect() 

//Will print: map contains ["FovCounted":"598", "ID":"1", "FovCount":"600"]

your problem is the fact that the contents between the tags will need to keep the same format throughout or this code will break

Vinny
Yes, I need to define different parser for my tags. Indeed, XmlParser will help to find tags name and use the good parser (by contents). Thanks
Fabien Barbier
A: 

Some nice groovy regexp examples: http://gr8fanboy.wordpress.com/2010/05/06/groovy-regex-text-manipulation-example/ http://pleac.sourceforge.net/pleac_groovy/patternmatching.html

FlareCoder