简体   繁体   English

Groovy grep + 构建键值

[英]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)我想要做的是 grep 的名称和消息(每次消息都与他之后出现的名称有关)

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.这是我可以在 powershell 中轻松完成的事情,但我在 groovy 方面没有经验,如果有人可以为我提供帮助,我很乐意。

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM