简体   繁体   English

Groovy为每个匹配返回一个数组

[英]Groovy returning an array for each match

I have strings in my logs in following pattern output:server-01-logs_20190401162454 , output:database-01-logs_20190401162454 . 我在以下模式output:server-01-logs_20190401162454日志中包含字符串output:server-01-logs_20190401162454output:database-01-logs_20190401162454 I need to match the string before the underscore( _ ) ie output:database-01-logs and output:server-01-logs . 我需要在下划线( _ )之前匹配字符串,即output:database-01-logsoutput:server-01-logs So I am using the following pattern: 所以我使用以下模式:

result = text =~ /output:([^_]+)/
Iterator<String> elements = result.iterator();
while (elements.hasNext()) {
  System.out.println(elements.next());
}

But the result I am getting is an array of match for each String like below 但是我得到的结果是每个字符串的匹配数组,如下所示

[output:server-01-logs, server-01-logs]
[output:database-01-logs, database-01-logs]

What I expect is 我期望的是

output:server-01-logs
output:database-01-logs

Can somebody help me with what I am missing here? 有人可以帮我解决我在这里所缺少的吗?

You may remove the capturing group (since it appears you do not want to get any submatches) and use 您可以删除捕获组(因为您似乎不想获得任何子匹配项)并使用

def text = "output:server-01-logs_20190401162454, output:database-01-logs_20190401162454"
def result = (text =~ /output:[^_]+/).collect()

See this Groovy demo . 请参阅此Groovy演示

Or, if you want to preserve the capturing group, collect Group 0 values: 或者,如果要保留捕获组,请收集组0值:

def text = "output:server-01-logs_20190401162454, output:database-01-logs_20190401162454"
def result = (text =~ /output:([^_]+)/).collect { it[0] }
print(result)

Output: 输出:

[output:server-01-logs, output:database-01-logs]

See Groovy demo . 请参阅Groovy演示

If you need the captured values, replace it[0] with it[1] . 如果需要捕获的值,请将it[0]替换it[1]

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

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