Devin Devin - 28 days ago 8
C# Question

C# Regex to match pattern [word] text (more)

I need a C# regex that can find a patter in a string.

This is the string:

[Tommy] wants 'gum' and [Johny's last name] is ('Smith', 'Doe', 'Black') and [money] is not ('char', 'string') and [Mr Smith's [right hand man]] is ('Johny', 'Tommy') and [Mr Smith] sales 'wine'


What I am looking to pull out is:

[Johny's last name] is ('Smith', 'Doe', 'Black')
[Mr Smith's [right hand man]] is ('Johny', 'Tommy')


Anything could be inside of the brackets and there could be an unlimited amount of items between the parentheses.

Answer

Can you confirm that this

public static void Main(string[] args)
{
    var text =
        @"[Tommy] wants 'gum' and [Johny's last name] is ('Smith', 'Doe', 'Black') and [money] is not ('char', 'string') and [Mr Smith's [right hand man]] is ('Johny', 'Tommy') and [Mr Smith] sales 'wine'";
    var pattern = @"((\[[^\]\[]*\])|(\[[^\[\]]*\[[^\[\]]*][^\[\]]*\])) is \(.*?\)";
    var regex = new Regex(pattern);
    var matches = regex.Matches(text);
    var listOfMatches = new List<string>();
    foreach (Match match in matches)
    {
        listOfMatches.Add(match.Value);
    }
}

is working for you?