Reputation: 1524
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 ?
Upvotes: 3
Views: 711
Reputation: 5310
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
Upvotes: 0
Reputation: 797
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
Upvotes: 2
Reputation: 75671
Try this:
def map = [:]
txt.replaceAll('<.+>', '').trim().eachLine { line ->
def parts = line.split(',')
map[parts[0].trim()] = parts[1].trim().toInteger()
}
Upvotes: 3