Willem
Willem

Reputation: 9486

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.

Upvotes: 3

Views: 5792

Answers (3)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56172

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

Upvotes: 3

Robin Maben
Robin Maben

Reputation: 23064

string pattern = Regex.Escape("[") + "(.*?)]";
string input = "Test [Test2] .. sample text [Test3] ";

MatchCollection matches = Regex.Matches(input, pattern);
var myResultList = new List<string>();
foreach (Match match in matches)
{
    myResultList.Add(match.Value);
}

The result list would contain : [Test2], [Test3]

Upvotes: 3

ykatchou
ykatchou

Reputation: 3727

Stallman says : "When you want to solve a problem using regexp, now you have two problems".

In your case it's something like ^\[.*\]$

http://www.regular-expressions.info/dotnet.html

http://regexlib.com/CheatSheet.aspx?AspxAutoDetectCookieSupport=1

Upvotes: 1

Related Questions