'Regex - capture groups inside group

I have a file text including this content:

define host {
  use            host-template
  host_name      server-01
  display_name   server-01-display-name
  address        10.0.0.1
  _CUSTOMEREMAIL [email protected]
  _LBZ           LBZ#10178541
}

define service {
  use                  host-template
  host_name            server-02
  service_description  server-02
  servicegroups        wlan
  display_name         server-02
  _LBZ                 LBZ#425964
  _TARGETIP            10.0.0.2
  _CUSTOMEREMAIL [email protected]
}

define service {
  use                  host-template
  host_name            server-03
  service_description  server-03
  servicegroups        wlan
  display_name         server-04
  _LBZ                 LBZ#421264
  _TARGETIP            10.0.0.3
  _CUSTOMEREMAIL [email protected]
}

define host {
  use            host-template
  host_name      server-04
  display_name   server-04
  address        10.0.0.4
  _CUSTOMEREMAIL [email protected]
  _LBZ           LBZ#12300541
}

Task: The server02 must be found by parameter "_LBZ" - in this case 425964. Once the define found, it should also capture parameters "host_name", "_LBZ" and '_CUSTOMEREMAIL'.

Wished result:

Can you help me, please? I am sitting here the second day with this expression.



Solution 1:[1]

Here is one way to do so:

{(?=[^}]*?host_name\s*([^\s]+))(?=[^}]*?_LBZ\s*LBZ#(425964))(?=[^}]*?_TARGETIP\s*([^\s]+))

See the online demo:


The first group will be host_name, the second _LBZ and the last _CUSTOMEREMAIL.


  • {: Matches {.
  • (?=): Positive lookahead.
    • [^}]*?: Matches any character other than }, between zero and unlimited times, as few as possible.
    • host_name: Matches host_name.
    • \s*: Matches any number of whitespaces.
    • (): Capturing group
      • [^\s]+. Matches any character other than a whitespace, between one and unlimited times, as much as possible.

The other two lookaheads are constructed similarly, to capture the other parameters.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1