0

How can I get a list of result of regex, in to a list?

I'll show my case as example: I have a the following HTML string code:

<div>
  <p>Hello World</p>
  <p>Hello Stackoverflow</p>
  <p>The book is on the table</p>
</div>

My regex filter is the following:

<p>(.*)</p>

The result that I'm looking for is the following list:

<p>Hello World</p>
<p>Hello Stackoverflow</p>
<p>The book is on the table</p>

How can I proceed to get that result?

Dan
  • 1,518
  • 5
  • 20
  • 48
  • 2
    I think [this link](http://stackoverflow.com/questions/3246237/how-to-find-multiple-occurrences-with-regex-groups) answers your question. :) – SamGhatak Feb 18 '16 at 19:23
  • You will have to use `capturing groups`. –  Feb 18 '16 at 19:25

2 Answers2

3

This gets us all the matches:

var allMatches = Regex.Matches(input, pattern);

Let's convert this IEnumerable to an IEnumerable<Match>. This is necessary because the MatchCollection class predates .NET generics:

var matchesTyped = allMatches.Cast<Match>();

Then we map the matches to the matched values and output the result into a list:

var matchedStrings = matchesTyped.Select(m => m.Value).ToList();

TL;DR

var result = Regex.Matches(input, pattern).Cast<Match>().Select(m => m.Value).ToList();
Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

This should works for you:

string str = "<div>" +
                "<p>Hello World</p>" +
                "<p>Hello Stackoverflow</p>" +
                "<p>The book is on the table</p>" +
             "</div>";

string pattern = "<p>.*?</p>";

var matches = Regex.Matches(str, pattern);

var result = matches.Cast<Match>().Select(m => m.Value.Trim()).ToArray();

foreach (var item in result)
{
    //do something
}

I changed the regular expression adding ? because it captures only one result from the first <p> until the last </p> in the string.

Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53