代码之家  ›  专栏  ›  技术社区  ›  Kcoder Bassam Alugili

如何在其他带括号的字符串中匹配带嵌套括号的字符串?

  •  0
  • Kcoder Bassam Alugili  · 技术社区  · 5 年前

    [2020][159]Debugging: [FIXED_RANDOM_324 - Some Text[R] Here[TM]][PRODUCTION1] - [192.0.0.1] - [Mozilla]
    [2021][532]Debugging: [FIXED_ABCDEF_21 - Simple][PRODUCTION2] - [192.0.0.32] - [Chrome]
    

    我需要得到 FIXED_RANDOM_324 - Some Text[R] Here[TM] FIXED_ABCDEF_21 - Simple

    "FIXED_" 部分遗嘱 总是一样的

    我试着用一些简单的东西比如 \[FIXED.*]\] 但这只起到了最重要的作用。

    1 回复  |  直到 5 年前
        1
  •  3
  •   Dmitrii Bychenko    5 年前

    你可以试试 @"FIXED.*?(?=\]\[)" 图案:

     FIXED  - fixed part
     .*?    - zero or more arbitrary characters (as few as posible)
     ][     - followed by ][ (but not included into the match) 
    

    演示:

      string[] tests = new string[] {
        "[2020][159]Debugging: [FIXED_RANDOM_324 - Some Text[R] Here[TM]][PRODUCTION1] - [192.0.0.1] - [Mozilla]",
        "[2021][532]Debugging: [FIXED_ABCDEF_21 - Simple][PRODUCTION2] - [192.0.0.32] - [Chrome]",
      };
    
      Regex regex = new Regex(@"FIXED.*?(?=\]\[)");
    
      var result = tests
        .Select(test => regex.Match(test))
        .Where(match => match.Success)
        .Select(match => match.Value);
    
      Console.Write(string.Join(Environment.NewLine, result));
    

    结果:

    FIXED_RANDOM_324 - Some Text[R] Here[TM]
    FIXED_ABCDEF_21 - Simple
    

    编辑: 如果我们想 打开和关闭括号我们必须使用更详细的模式,例如。

     @"FIXED(?:.*?(?<o>\[)?.*?(?<-o>\])?.*?)*(?=\])"
    

    (?<o>\[) (?<-o>\]) 匹配 开放 以及相应的 关闭 括号:

      string[] tests = new string[] {
        "[2020][159]Debugging: [FIXED_RANDOM_324 - Some Text[R] Here[TM]][PRODUCTION1] - [192.0.0.1] - [Mozilla]",
        "[2021][532]Debugging: [FIXED_ABCDEF_21 - Simple][PRODUCTION2] - [192.0.0.32] - [Chrome]",
        "[2021][532]Debugging: [FIXED_XYZ_02 - [Some][Text]][PRODUCTION2] - [192.0.0.32] - [Chrome]",
        "[2021][532]Debugging: [FIXED_XYZ_02 - [Some][Text] more][PRODUCTION2] - [192.0.0.32] - [Chrome]",
      };
    
      Regex regex = new Regex(@"FIXED(?:.*?(?<o>\[)?.*?(?<-o>\])?.*?)*(?=\])");
    
      var result = tests
        .Select(test => regex.Match(test))
        .Where(match => match.Success)
        .Select(match => match.Value);
    
      Console.Write(string.Join(Environment.NewLine, result));
    

    结果:

    FIXED_RANDOM_324 - Some Text[R] Here[TM]
    FIXED_ABCDEF_21 - Simple
    FIXED_XYZ_02 - [Some][Text]
    FIXED_XYZ_02 - [Some][Text] more