Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a array/list using regex

I would like to return a array string[] or a list List<string> using regex.

I want to compare a string and return all values that starts with [ and end with ].

I am new to regex, so would you please explain the syntax that you will be using to produce the right results.

like image 459
Willem Avatar asked Aug 11 '26 12:08

Willem


1 Answers

var result = Regex.Matches(input, @"\[([^\[\]]*)\]")
    .Cast<Match>()
    .Select(m => m.Groups[1].Value).ToArray();

This regex \[([^\[\]]*)\] means:

  1. \[ - character [
  2. ([^\[\]]*) - any character, excluding [] any number of repetitions, group 1
  3. \] - character ]

Update:

var result = Regex.Matches(input, @"\[[^\[\]]*\]")
    .Cast<Match>()
    .Select(m => m.Value).ToArray();
like image 180
Kirill Polishchuk Avatar answered Aug 13 '26 02:08

Kirill Polishchuk