C # Regex: Returns collection of results
string: "<something><or><other>"
regex pattern: "<(\w+)><(\w+)><(\w+)>"
How do I create a regex call that returns me a collection of results containing everything between the parentheses? For example, I need a result set {"something", "or", "other"}.
For bonus points, what is called? Capturing? Capturing groups? Some kind of template? It seems to me that if I knew the correct terminology I could find.
Thank.
These are commonly referred to as capture groups, and you can receive captures as shown:
Regex regex = new Regex(@"some (pattern)");
Match m = regex.Match("some pattern");
foreach (Capture c in m.Groups) {
Console.WriteLine(c.Value); // write the value to the console "pattern"
}
m.Groups.Count
will tell you how many groups match, m.Groups[0]
will always be the full match text.
source to share
I think what you are looking for is MatchCollection
:
Represents the set of successful matches found by iteratively applying a regular expression pattern to an input string.
Example:
string input = "<something><or><other>";
string pattern = "(?<=<)[^>]*(?=>)";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.ToString()); // do something with match here
}
Edit: Changed regex: <(\w+)><(\w+)><(\w+)>
to this:(?<=<)[^>]*(?=>)
source to share
Use MatchCollection. EDIT: Forgot to change the regex to what you were asking for. The code below generates the following output:
something
or
other
Is this what you were looking for?
static void Main(string[] args)
{
var str = "<something><or><other>";
var re = new Regex(@"(\w+)");
MatchCollection mc = re.Matches(str);
foreach (Match m in mc)
{
Console.WriteLine(m.Value);
}
}
source to share
There are many ways to trick this cat:
using System;
using System.Text.RegularExpressions;
namespace Test
{
class Test
{
static void Main(string[] args)
{
string target = @"<something><or><other>";
// One group, many matches
Regex r1 = new Regex(@"<(\w+)>");
MatchCollection mc = r1.Matches(target);
foreach (Match m in mc)
{
Console.WriteLine(m.Groups[1].Value);
}
Console.WriteLine();
// One match, many groups
Regex r2 = new Regex(@"<(\w+)><(\w+)><(\w+)>");
Match m2 = r2.Match(target);
if (m2.Success)
{
foreach (Group g in m2.Groups)
{
Console.WriteLine(g.Value);
}
}
Console.WriteLine();
// One group, one match, many captures
Regex r3 = new Regex(@"(?:<(\w+)>)+");
Match m3 = r3.Match(target);
if (m3.Success)
{
foreach (Capture c in m3.Groups[1].Captures)
{
Console.WriteLine(c.Value);
}
}
Console.WriteLine();
// Many matches, no groups, no captures
Regex r4 = new Regex(@"(?<=<)\w+(?=>)");
foreach (Match m in r4.Matches(target))
{
Console.WriteLine(m.Value);
}
Console.ReadLine();
}
}
}
source to share