【问题标题】:How represent block of text with regex? [duplicate]如何用正则表达式表示文本块? [复制]
【发布时间】:2019-10-24 20:39:35
【问题描述】:

我正在尝试使用 C# 使用已知模式解析文本。我有以下文字

Fn.StartIf(some condition) 

Block of blob text. This text could start with a new line or it may not... This text could be anything including numbers and special characters number like 123.

and it multiple lines of text and could end with a new line or not. 
Fn.EndIf

最后,我想得到以下组:

  1. (第 1 组)Fn.StartIf(某些条件)
  2. (第 2 组)某些情况
  3. (第 3 组)中间的所有文本
  4. (第 4 组)Fn.EndIf

这是我尝试过的(Fn.StartIf\((.+)\))^(.+|\n*|\s*)$(Fn.EndIf)。但是,^(.+|\n*|\s*)$ 模式并没有抓取 Fn.StartIf(some condition) 之后和 Fn.EndIf 之前的所有 blob 文本

如何正确抓取Fn.StartIf(some condition)Fn.EndIf 之前的所有blob 文本?

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    您可以使用以下模式:

    (Fn\.StartIf\((.+?)\))([\S\s]+)(Fn\.EndIf)
    

    Demo.

    需要注意的几点:

    • . 匹配 任何 字符。您应该使用 \. 来匹配文字点。

    • 在括号内使用惰性匹配 (.+?) 以避免匹配嵌套括号(如果找到)。

    • 要匹配任何字符(包括空白字符),您可以使用[\S\s]

    C# 示例:

    string input = "Fn.StartIf(some condition) \n\nBlock of blob text. This text could start with a new line or it may not... This text could be anything including numbers and special characters number like 123.\n\nand it multiple lines of text and could end with a new line or not. \n\nFn.EndIf";
    
    string pattern = @"(Fn\.StartIf\((.+?)\))([\S\s]+)(Fn\.EndIf)";
    Match match = Regex.Match(input, pattern);
    
    if (match != null)
    {
        for (int i = 1; i <= match.Groups.Count; i++)
        {
            Console.WriteLine($"Group #{i}: {match.Groups[i].Value}");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 2018-06-12
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多