【问题标题】:C# split large string with Regex.Split. Must keep delimitersC# 使用 Regex.Split 拆分大字符串。必须保留分隔符
【发布时间】:2021-03-02 04:07:34
【问题描述】:

我正在尝试使用正则表达式将一堵文本墙拆分为一个数组,它运行良好,但我不希望它删除我正在使用的分隔符。我研究了前瞻功能,但我无法让它正常工作或根本无法工作。

我有以下正则表达式,它在以下组合“Artículo #.”、“Artículo ##.”、1)、2) 等和 a)、b)、c) 以及“Párrafo”一词处拆分。

var result = Regex.Split(text, @"(Artículo)\s[0-9](.)|(Artículo)\s[0-9][0-9](.)|[a-z](\))|[1-9](\))|[1-9][0-9](\))|(Párrafo)", RegexOptions.None);

我需要保留我用来拆分的关键字。例如我有以下文字

Artículo 1. This is a test that includes : 1) Sample text 2) Sample text

最近我得到了:

 This is a test that includes :
 Sample text
 Sample text

我需要什么:

Artículo 1. This is a test that includes :
1) Sample text
2) Sample text

我觉得我快要接近了,但任何帮助都会很棒。

【问题讨论】:

  • 除了拆分之外,您还可以使用Regex.Match捕获组。这样您就可以遍历匹配项,并查看使用了哪个分隔符

标签: c# regex split


【解决方案1】:

你可以使用

var text = "Artículo 1. This is a test that includes : 1) Sample text 2) Sample text";
var result = Regex.Split(text, @"(?!^)\s+(?=\bArtículo\s+[0-9]+\.|[a-z]\)|[1-9]\d?\)|\bPárrafo\b)", RegexOptions.None);
Console.WriteLine(string.Join("\n", result));
// => Artículo 1. This is a test that includes :
// => 1) Sample text
// => 2) Sample text

请参阅C# demoregex demo

正则表达式是

(?!^)\s+(?=\bArtículo\s+[0-9]+\.|[a-z]\)|[1-9]\d?\)|\bPárrafo\b)

匹配

  • (?!^) - 字符串开头以外的位置
  • \s+ - 1+ 个空格(如果您使用\s*,则需要在Regex.Split 调用之后添加.Where(x => !string.IsNullOrEmpty(x))
  • (?=\bArtículo\s+[0-9]+\.|[a-z]\)|[1-9]\d?\)|\bPárrafo\b) - 紧随其后的位置
    • \bArtículo\s+[0-9]+\.| - 整个单词 Artículo、1+ 个空格、1+ 个 ASCII 数字和一个 .,或
    • [a-z]\)| - 小写 ASCII 字母和 ),或
    • [1-9]\d?\)| - 一个非零数字,然后是一个可选数字和一个),或者
    • \bPárrafo\b - 一个完整的词Párrafo

【讨论】:

  • 感谢您的精彩解释和代码。效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 2016-11-26
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
相关资源
最近更新 更多