Home > other >  Regex - capture groups inside group
Regex - capture groups inside group

Time:03-16

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.

CodePudding user response:

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.

  • Related