【问题标题】:REGEX Split string into List using keywordREGEX 使用关键字将字符串拆分为列表
【发布时间】:2020-03-03 16:36:57
【问题描述】:

我有如下字符串,我需要将字符串拆分为列表

string s = "Welcome to the Center

Batch #1 
English
Description about the course

Batch #2
Science
Description about the course

Batch #3
Social 
Description about the course "

我想使用"Batch" 关键字拆分字符串,输出应如下所示。如何使用正则表达式进行拆分?

myList[0]="Batch #1 
English
Description about the course"

myList[1]="Batch #2
Science
Description about the course"

myList[2]="Batch #3 
Social
Description about the course"

【问题讨论】:

标签: c# regex list split


【解决方案1】:

您可以尝试以下方法:-

List<string> strList = Regex.Split(str, "Batch").Skip(1).ToList();

【讨论】:

  • 拆分后列表中缺少“批处理”一词
  • 是的,在每个项目上附加“Batch”关键字都可以。
  • List strList = Regex.Split(str, "Batch").Skip(1).Select(x => "Batch" + x).ToList();
【解决方案2】:

您不需要正则表达式,只需将字符串拆分为两个连续的换行符(准确地说是\r\n\r\n 序列):

  string s = @"Welcome to the Center

  Batch #1 
  English
  Description about the course

  Batch #2
  Science
  Description about the course

  Batch #3
  Social
  Description about the course ";

  var splitted = s.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
  splitted.RemoveAt(0);

【讨论】:

    【解决方案3】:

    试试这个。

    你应该使用.*?

    Batch.*?course
    

    或

    Batch.*?.\n.*\n.*
    

    FIDDLE DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      • 2015-02-07
      • 2015-09-01
      • 2011-11-13
      • 1970-01-01
      相关资源
      最近更新 更多