简体   繁体   中英

Select all words inside brackets (multiple matches)

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

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM