代码之家  ›  专栏  ›  技术社区  ›  gilliduck

从一个特定的词分裂成另一个特定的词

  •  0
  • gilliduck  · 技术社区  · 4 年前

    假设一个字符串 Foo: Some Text Bar: Some Other Text FooBar: Even More Text

    Foo: Some Text
    Bar: Some Other Text
    FooBar: Even More Text
    

    我根本搞不懂它的正则表达式。我可以根据我想说的话来拆分它 (Foo:)|(Bar:)|(FooBar:) 但我不知道如何从每个组的开头到下一组的开头(如果是最后一组,则为文本结尾)。

    1 回复  |  直到 4 年前
        1
  •  1
  •   Wiktor Stribiżew    4 年前

    你可以用 Regex.Split

    (?<!^)\s+(?=\b(?:Bar|Foo(?:Bar)?):)
    

    regex demo . 细节:

    • (?<!^) -不是在字符串的开头
    • \s+ -1个或多个空白
    • (?=\b(?:Bar|Foo(?:Bar)?):)
      • \b -字界
      • (?:Bar|Foo(?:Bar)?) - Bar Foo FooBar
      • : -结肠。

    C#演示:

    var s = "Foo: Some Text Bar: Some Other Text FooBar: Even More Text";
    var res = Regex.Split(s, @"(?<!^)\s+(?=\b(?:Bar|Foo(?:Bar)?):)");
    Console.WriteLine(string.Join("\n", res));
    

    Foo: Some Text
    Bar: Some Other Text
    FooBar: Even More Text
    

    另一个主意 :将冒号前的任何单词和下一个单词与 之后:

    var matches = Regex.Matches(s, @"\w+(?:-\w+)*:.*?(?=\s*(?:\w+(?:-\w+)*:|$))", RegexOptions.Singleline)
        .Cast<Match>()
        .Select(x => x.Value)
        .ToList();
    

    this regex demo .

    细节

    • \w+(?:-\w+)*: -1个或多个单词字符(字母/数字/下划线),然后重复0个或更多个 - 和1个以上的字符
    • .*? -任何0个或更多字符,尽可能少
    • (?=\s+(?:\w+(?:-\w+)*:|$))
      • \s* -0个或更多空白
        • (?:\w+(?:-\w+)*: -一个或多个单词字符(字母/数字/下划线),然后重复0个或更多个 -
      • | -或者
        • $ -字符串末尾
      • )

    C# demo .