Reputation: 407
I need to split a string in C#. I think it is better to see the next example:
string formula="[[A]]*[[B]]"
string split = Regex.Match(formula, @"\[\[([^)]*)\]\]").Groups[1].Value;
I would like to get a list of strings with the word contained between '[[' and ']]' so, in this case, I should get 'A' and 'B', but I am getting this: A]]*[[B
Upvotes: 0
Views: 1149
Reputation: 39329
The *
matches as much as possible of the expression before it. Use a *?
to match the smallest possible match.
See http://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx#quantifiers
So your regex should be @"\[\[([^)]*?)\]\]"
Also, use Regex.Matches
rather than Regex.Match
, to get them all.
Upvotes: 1
Reputation: 25370
Your main problem is that Regex.Match will match the first occurrence, and stop. From the documentation:
Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.
You want Regex.Matches to get them all. This regex will work:
\[\[(.+?)\]\]
It will capture anything between [[
and ]]
so your code could look like:
string formula = "[[A]]*[[B]]";
var matches = Regex.Matches(formula, @"\[\[(.+?)\]\]");
var results = (from Match m in matches select m.Groups[1].ToString()).ToList();
// results contains "A" and "B"
Upvotes: 2