正则表达式以匹配段落

时间:2019-02-27 11:26:17

标签: c# regex

我有这段文字:

Terms: 1 I've got the {name} and {term}
    So I would like to go
    But not return

Terms: 2 I've got the {name} and {term}
    So I would like to go
    But not return

Terms: 3 I've got the {name} and {term}
    So I would like to go
    But not return

我想匹配定义为Terms:2 or more newlines结尾的每个段落。

The closest I can get appears to be

/(terms:).*(\n)*/gim

如何将每个段落作为一个单独的组返回?

2 个答案:

答案 0 :(得分:2)

您可以使用

(?sim)^terms:.*?(?=(?:\r?\n){2,}|\z)

请参见.NET regex demo

详细信息

  • (?sim)-启用RegexOptions.SinglelineRegexOptions.IgnoreCaseRegex.Multiline选项
  • ^-一行的开头
  • terms:-文字子字符串
  • .*?-任意0个以上的字符,尽可能少
  • (?=(?:\r?\n){2,}|\z)-紧跟2个或更多换行符(CRLF或LF)序列或字符串结尾的位置。

用法

var results = Regex.Matches(s, @"(?sim)^terms:.*?(?=(?:\r?\n){2,}|\z)")
    .Cast<Match>()
    .Select(x => x.Value)
    .ToList();

或者,使用两个或多个换行符进行拆分

(?:\r?\n){2,}

请参见this .NET regex demo。它仅匹配2个或多个重复的可选CR和LF符号。

用法

var results = Regex.Split(s, @"(?:\r?\n){2,}");

答案 1 :(得分:0)

也许您可以尝试类似的方法。

(terms:.*\n.*\n.*(\n|))

https://regex101.com/r/5Dzp1F/1/

相关问题