将String转换为Map

时间:2013-07-17 04:46:31

标签: groovy

def val = "[name: searchBaseDN value: , name: enable value: false, name: userDn value:  
cn=EAGREAD,ou=Users,ou=Administration,o=hyn, name: base value:  , name: prefsize value: 1,   
name: timeBetweenEvictionRuns value: 300000]"

我想将其转换为hashmap val [name:value]

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这看起来很有希望:

matches = val =~ /name:\s+(.*?)\s+value:\s+(.*?)(,\s+|\s+|])/

def newVal = [:]
matches.each { m ->
    newVal[m[1]] = m[2]
}

但是如果字符串略有改变,正则表达式可能会破坏......