I'm working on a little project and this is my first time using regex
I've tried using .match or .matches but i don't see any option that will alow me to return the results of a regex query to an array.
thanks
I'm working on a little project and this is my first time using regex
I've tried using .match or .matches but i don't see any option that will alow me to return the results of a regex query to an array.
thanks
If you use Regex.Matches(input,regex,regexoptions)
it will return a collection of matches that you can then iterate through.
A collection is seen as a better thing to use for developing (http://msdn.microsoft.com/en-us/library/k2604h5s(VS.71).aspx)
I haven't tested it but something like that will do the job :
public static IEnumerable<Match> GetMatches(Regex regex, string input)
{
var m = regex.Match(input);
while (m.Success)
{
yield return m;
m = m.NextMatch();
}
}
Use the Matches CopyTo method to copy to the array of your choice.
Have a look at this
Edit to comment
Something like this
Regex rg = new Regex("YourExpression");
MatchCollection matcheCollection = rg.Matches("Your String");
Match[] matches = new Match[matcheCollection.Count];
matcheCollection.CopyTo(matches, 0);
Regex rg = new Regex("YourExpression");
Match[] result = rg.Matches("Your String").OfType<Match>().ToArray();
Would save you from having to define the Match[] separably.