anbuselvan
anbuselvan

Reputation: 1241

Regular Expressions match any string between [ and ]

I want to match any string between [ and ]. Following code working fine but i want to output with out this symbol [ ]

my code:

    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);
        }
    }

Upvotes: 4

Views: 7780

Answers (2)

Kibbee
Kibbee

Reputation: 66112

You'll want to use Match.Groups property. Since you are already using brackets, you can get the group you want with

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

Groups[0] will contain the whole string with the [ and ].

Also, I think your regex can be simplified

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

should be equivalent to

\[(.*?)\]

since .* will match anything, including white space, which is what \s covers.

Upvotes: 5

Richard Fearn
Richard Fearn

Reputation: 25481

Try

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

This gives you the value of the first captured group - the contents of the outer parantheses.

Upvotes: 1

Related Questions