0

I have a text string with a custom macro:

"Some text {MACRO(parameter1)} more text {MACRO(parameter2)}"

In order to process the macro I want to split the string like that:

expected result

"Some text "
"{MACRO(parameter1)}"
" more text "
"{MACRO(parameter2)}"

I've tried to split the string using Regex.Split()

public static string[] Split(string input)
{
    var regex = new Regex(@"{MACRO\((.*)\)}");
    var lines = regex.Split(input)
    return lines;
}

However Regex.Split() deletes the match itself and gives me the following:

actual result

"Some text "
" more text "

I know I could parse the string doing iterations of .Match() and .Substring()

But is there an easy way get the result along with the matches?

enkryptor
  • 1,574
  • 1
  • 17
  • 27

1 Answers1

0

Try this

            string input = "Some text {MACRO(parameter1)} more text {MACRO(parameter2)}";
            string pattern = @"(?'text'[^\{]+)\{(?'macro'[^\}]+)\}";
            MatchCollection matches = Regex.Matches(input, pattern);
            foreach (Match match in matches)
            {
                Console.WriteLine("text : '{0}'; macro : '{1}'", match.Groups["text"].Value.Trim(), match.Groups["macro"].Value.Trim());
            }
            Console.ReadLine();
jdweng
  • 33,250
  • 2
  • 15
  • 20