How to get the text contains square brackets in square brackets?

2.2k views Asked by At

I have a string like

string str = "[COUNT([Weight] > 10)] < 20 AND [COUNT([Height] < 10)] < 25";

And I want to get the value in square bracket. If I use expression Regex(@"\[.*?\]") => it returns

[COUNT([Weight] and [COUNT([Height]

but I want to get the value

[COUNT([Weight] > 10)] and [COUNT([Height] < 10)]

Could I do that? Please assist me.

Thanks!

3

There are 3 answers

0
Rahul Tripathi On

You can try this regex:

var pattern = @"\[.*\]";

REGEX DEMO

1
Avinash Raj On

You may use this regex.

@"\[(?:\[[^\[\]]*\]|[^\[\]])*\]"

DEMO

(?:\[[^\[\]]*\]|[^\[\]])* (Matches [..] block or any char but not of [ or ] ) , zero or more times.

2
Soner Gönül On

How about without regex?

string str = "[COUNT([Weight] > 10] < 20";
var start = str.IndexOf('[');
var end = str.LastIndexOf(']');
Console.WriteLine(str.Substring(start, end - start + 1));

enter image description here