简体   繁体   中英

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 . I need to match the string before the underscore( _ ) ie output:database-01-logs and output: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 .

Or, if you want to preserve the capturing group, collect Group 0 values:

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 .

If you need the captured values, replace it[0] with it[1] .

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