lowdegeneration lowdegeneration - 2 months ago 9
C# Question

match particular words with regex inside array like string in c#

string inputText = "{\"(text1, text2)\",\"(text3, text4)\",\"(text5, text6)\"}";


I need a regex pattern that will match
text1
,
text3
and
text5
strings? (
text1
text2
text3
,
text4
,
text5
,
text6
are just random words that come from database).

What would this regex pattern be?

Note: I dont know what is inside inputText.So i can not define like text1, text2, text3 in regex pattern.

Answer

Try this

            string inputText = "{\"(text1, text2)\",\"(text3, text4)\",\"(text5, text6)\"}";
            string pattern = @"\((?'word'[^,]+)|,\s+(?'word'[^\)]+)";
            MatchCollection matches = Regex.Matches(inputText, pattern);
            foreach (Match match in matches)
            {
                Console.WriteLine(match.Groups["word"].Value);
            }
            Console.ReadLine();