Regular expressions match any string between [and]

I want to match any string between [and]. After the code works fine, but I want to output with this character []

my code is:

    string strValue = "{test}dfdgf[sms]";// i want to sms

    private void Form1_Load(object sender, EventArgs e)
    {
        Match mtch = Regex.Match(strValue, @"\[((\s*?.*?)*?)\]");
        if (mtch.Success)
        {
            MessageBox.Show(mtch.Value);
        }
    }
+3
source share
2 answers

You want to use the Match.Groups property . Since you already use parentheses, you can get the desired group with

MessageBox.Show(mtch.Groups[1].Value);

Groups [0] will contain the entire line with [and].

Also, I think your regex could be simplified

\[((\s*?.*?)*?)\]

should be equivalent

\[(.*?)\]

as. * will match anything, including a space, which is.

+4
source

Try

MessageBox.Show(mtch.Groups[1].Value);

This gives you the meaning of the first captured group - the contents of the outer brackets.

+1

Source: https://habr.com/ru/post/1763219/


All Articles