简体   繁体   English

正则表达式 - 捕获组内的组

[英]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 customer01@mail.com
  _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 customer5@mail.com
}

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 customer01@mail.com
}

define host {
  use            host-template
  host_name      server-04
  display_name   server-04
  address        10.0.0.4
  _CUSTOMEREMAIL customer02@mail.com
  _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'.任务:必须通过参数“_LBZ”找到 server02 - 在本例中为 425964。一旦找到定义,它还应该捕获参数“host_name”、“_LBZ”和“_CUSTOMEREMAIL”。

Wished result:希望的结果:

  • server-02服务器-02
  • 425964 425964
  • customer5@mail.com customer5@mail.com

Can you help me, please?你能帮我吗? I am sitting here the second day with this expression.第二天,我带着这种表情坐在这里。

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 .第一组是host_name ,第二组是_LBZ ,最后_CUSTOMEREMAIL


  • { : Matches { . { :匹配{
  • (?=) : Positive lookahead. (?=) :正面前瞻。
    • [^}]*? : Matches any character other than } , between zero and unlimited times, as few as possible. : 匹配除}之外的任何字符,次数介于零次和无限次之间,尽可能少。
    • host_name : Matches host_name . host_name :匹配host_name
    • \s* : Matches any number of whitespaces. \s* :匹配任意数量的空格。
    • () : Capturing group () : 捕获组
      • [^\s]+ . [^\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.其他两个 lookaheads 的构造类似,以捕获其他参数。

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

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