tags:

views:

83

answers:

4

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

A: 

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)

AutomatedTester
A: 

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();
    }
}
Petar Petrov
I get the error: cannot be an iterator block because 'IEnumerable<System.Text.RegularExpressions.Match>' is not an iterator interface type
Crash893
It works perfectly fine for me. I use it like this : var re = new Regex(@"download"); foreach (var m in GetMatches(re, @"download download download download")) { Console.WriteLine(m.Value); } and it prints 4 times the string "download".
Petar Petrov
A: 

Use the Matches CopyTo method to copy to the array of your choice.

Have a look at this

MatchCollection.CopyTo Method

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);
astander
so something like Reg.matches(htmlcode).copyto(newarray);
Crash893
See updated answer.
astander
Thanks for that. I guess I'm confused as to why i can't go directly to a string[] rather than jumping through hoops with matches. If my regex has (...) in it should it not be returning matches as string text? thanks again
Crash893
A: 
Regex rg = new Regex("YourExpression");

Match[] result = rg.Matches("Your String").OfType<Match>().ToArray();

Would save you from having to define the Match[] separably.

runrunraygun