Convert result of matches from regex into list of string
Solution 1:
With the Regex you have, you need to use Regex.Matches
to get the final list of strings like you want:
MatchCollection matchList = Regex.Matches(Content, Pattern);
var list = matchList.Cast<Match>().Select(match => match.Value).ToList();
Solution 2:
To get just a list of Regex matches, you may:
var lookfor = @"something (with) multiple (pattern) (groups)";
var found = Regex.Matches(source, lookfor, regexoptions);
var captured = found
// linq-ify into list
.Cast<Match>()
// flatten to single list
.SelectMany(o =>
// linq-ify
o.Groups.Cast<Capture>()
// don't need the pattern
.Skip(1)
// select what you wanted
.Select(c => c.Value));
This will "flatten" all the captured values down to a single list. To maintain capture groups, use Select
rather than SelectMany
to get a list of lists.
Solution 3:
A possible solution using Linq:
using System.Linq;
using System.Text.RegularExpressions;
static class Program {
static void Main(string[] aargs) {
string value = "I have a dog and a cat.";
Regex regex = new Regex("dog|cat");
var matchesList = (from Match m in regex.Matches(value) select m.Value).ToList();
}
}