How to regex from pattern X to the next occurrence of X, recursively, getting the content between as matches

With regex, by doing (?s)X(.*?)Y on the following strings:

X
aaa
Y
X
bbb
Y
X
ccc
Y

I get:

Match1.Group1: "aaa"  
Match2.Group1: "bbb"  
Match3.Group1: "ccc"

I’d like to get the same result (matches and groups) with the following:

X
aaaa
X
bbbb
X
cccc

But I cannot wrap my head around how to do that. Thank you for taking the time to read and reply.

I’ve tried everything I can think. I use C# language and https://regex101.com/ to test the regex statement.

check this out:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string input = "X\naaaa\nX\nbbbb\nX\ncccc";

        //modify the regex pattern to exclude "X"
        string pattern = @"(?s)X((?:(?!X).)*)";

        //matching the pattern in the input string
        MatchCollection matches = Regex.Matches(input, pattern);

        for (int i = 0; i < matches.Count; i++)
        {
            Console.WriteLine($"Match{i + 1}.Group1: \"{matches[i].Groups[1].Value}\"");
        }
    }
}

Output:

Match1.Group1: "aaaa"
Match2.Group1: "bbbb"
Match3.Group1: "cccc"

Without Regex:

string txt = "X\naaaa\nX\nbbbb\nX\ncccc";
string[] matches = txt.Replace("\n",null).Split(new string[] {"X"}, StringSplitOptions.RemoveEmptyEntries);
foreach (string match in matches) {
    Console.WriteLine(match);
}

Leave a Comment