c# validate that string contains matching number of brackets

c#, linq, regex, string, validation

Solution

Because you don't allow nesting, you can use a regex:

^([^[\]]*\[[^[\]]*\]){0,3}[^[\]]*$

Explanation:

- `(...){0,3}` matches up to three sets of the following:

- `[^[\]]*` matches optional non-bracket characters

- `\[` matches `[` to open a group

- `[^[\]]*` matches optional non-bracket characters inside the group

- `\]` matches `]` to close the group

- Finally, `[^[\]]*` matches more optional non-bracket characters after all of the groups

Problem

If I have a string like this... ``` "123[1-5]553[4-52]63244[19-44]" ``` ...what's the best way to validate the following conditions: - Every open bracket has a matching close bracket - There are no more than 3 sets of brackets - There are no nested brackets (i.e., [123-[4]9]) Would a regex be able to validate all of these scenarios? If not, how about LINQ?

Original source