0
votes

I have some output from a call to a backend server (DSDB) using the unix shell .execute command in groovy. What it gives me is a list of key value pairs separated by a line and each pair separated by a colon. I need to have each Key Value pair placed into a map. This is the output I receive:

Group Name:  groupName
       GID:  12345
      Type:  1
  Comments:
Visibility:  visibile1
Owner Name:  name1
Owner Number:  123
Manager Name:  manager1
Manager Number:  234
Environment:  dev
     State:  0

I need to get the value of Owner Name within a function and pass it back as a variable and I also need the value of environment in another function. These will be two separate functions.

1
You should show the code that you have written so far. You can split the string by line and each line by the first colon without any regex. Unless you have multi line values for"comments:" - tkruse
Consider existing questions like this stackoverflow.com/questions/2812689/… - tkruse

1 Answers

1
votes

Couldn't find a regex that would do all of that, but a bit of groovy fixes that:

final data = """
Group Name:  groupName
       GID:  12345
      Type:  1
  Comments:
Visibility:  visibile1
Owner Name:  name1
Owner Number: 123
Manager Name: manager1
Manager Number: 234
Environment: dev
State: 0
"""

final a = (data =~ /\s*([^:]+):(.*)/) 
    .collect { [it[1], it[2].trim()] }
    .collectEntries()

assert a["Owner Name"] == "name1"
assert a["Environment"] == "dev"

Java patterns are in "single line mode" by default. This regex is matching keys and values separated by colon and finds a match for each line.

The collect then maps the matches into tuples. I'm also abusing this step to strip the leading space from the values (except from "Comments" field, which doesn't have a value).

Finally, collectEntries can be used to map the list of tuples into a single map.