简体   繁体   中英

Groovy grep + build key value

I have a variable holding the following text:

blablablabla
blablablabla
blablablabla
messages: 30
name: muzi
blablablabla
blablablabla
blablablabla
messages: 20
name: puzi
blablablabla
blablablabla
blablablabla
.
.
.

What i want to do is to grep the name and messages (every time the messages is related to the name that comes up right after him)

and set it up in data (switch name and messages) for example key value pair so i would have

Data = [
"muzi": 30
"puzi": 20
]

And so one. This is something that i can easily do in powershell but i have no experience in groovy and id love if someone can offer me some help.

def lines='''
blablablabla
blablablabla
blablablabla
messages: 30
name: muzi
blablablabla
blablablabla
blablablabla
messages: 20
name: puzi
blablablabla
blablablabla
blablablabla
messages: 11
name: puz
'''.readLines()

//Like this
def messages = lines.findAll{ it=~/^messages:\s+/ }.collect{ it.split(/:\s+/)[1] }
def names = lines.findAll{ it=~/^name:\s+/ }.collect{ it.split(/:\s+/)[1] }
def res = [names,messages].transpose().collectEntries()
println res

//OR like this:
res = lines.findAll{ it=~/^(messages|name):\s+/ }.collect{ it.split(/:\s+/)[1] }.collate(2).collectEntries{[it[1], it[0]]}
println res

You can use multiline regexp, which enforces that the two lines are consecutive . See the negative data at the beginning of the string.

String txt = """
messages: 300
blablablabla
name: zeny
blablablabla
blablablabla
messages: 30
name: muzi
blablablabla

blablablabla
messages: 20
name: puzi
blablablabla
"""

def res = [:]

txt.findAll(/(?ms)^messages: (\d+)$.^name: (\w+)$/) {match, w1, w2 -> res[w2] = w1}

assert res == [muzi:'30', puzi:'20']

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