Convert result of matches from regex into list of string

Related searches

How can I convert the list of match result from regex into List<string>? I have this function but it always generate an exception,

Unable to cast object of type 'System.Text.RegularExpressions.Match' to type 'System.Text.RegularExpressions.CaptureCollection'.

public static List<string> ExtractMatch(string content, string pattern)
    List<string> _returnValue = new List<string>();
    Match _matchList = Regex.Match(content, pattern);
    while (_matchList.Success)
        foreach (Group _group in _matchList.Groups)
            foreach (CaptureCollection _captures in _group.Captures) // error
                foreach (Capture _cap in _captures)
    return _returnValue;

If I have this string,

I have a dog and a cat.



I want that the function will return of result into List<string>


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();

How to convert matched Regex patterns to String? - Build, Use the Regex.Matches method to extract substrings based on patterns. It uses an input string that contains several words. Each one starts Foreach: We use foreach on the MatchCollection, and then on the result of the Captures property. Free online regular expression matches extractor. Just enter your string and regular expression and this utility will automatically extract all string fragments that match to the given regex. There are no ads, popups or nonsense, just an awesome regex matcher. Load a string, get regex matches. Created for developers by developers from team

Cross-posting answer from Looping through Regex Matches --

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
                // flatten to single list
                .SelectMany(o =>
                    // linq-ify
                        // don't need the pattern
                        // 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.

Regex.Match Method (System.Text.RegularExpressions), try this. Hide Copy Code. mc.OfType<Match>().ToList().ForEach(m => { clsList. AddRange(m.Groups[1].Value.Split(' ')); }); clsList = clsList. Dim kvpList As New List (Of KeyValuePair (Of String,System.Text.RegularExpressions.Regex)) patterns.ForEach (Sub§ kvpList.Add (New KeyValuePair (Of String,Regex) (p,New Regex§))) Dim ib As String = InputBox ((“Enter a string to compare to your pattern” & vbNewLine & “The first pattern matched will be prompted”))

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();

C# Regex.Matches Method: foreach Match, Capture, The above regex expression will match the text string, since we are trying to match a string of In the output, you can see that the first word i.e. The is returned. On the other hand, the findall function returns a list that contains all the matched� World's simplest browser-based utility for extracting regex matches from text. Load your text in the input form on the left, enter the regex below and you'll instantly get text that matches the given regex in the output area. Powerful, free, and fast. Load text – get all regexp matches. Created by developers from team Browserling.

Here's another solution that will fit into your code well.

while (_matchList.Success)
    _matchList = _matchList.NextMatch();

[Solved] How to convert the match collection values to list using linq , Returns a string with the contents of the n-th match in a match_results object that is ready. The object returned by str is of the basic_string corresponding to the type of the characters in the target sequence, even if the match_results object is filled using other types of character sequences, like the C-strings used in cmatch.

Historically the Regex collections have not implemented the generic collection interfaces, and the LINQ extension methods you're using operate on the generic interfaces. MatchCollection was updated in .NET Core to implement IList, and thus can be used with the Selectextension method, but when you move to .NET Standard 2.0, that interface implementation isn't there, and thus you can't just callSelect. Instead, you'll need to use the LINQ Cast or OfType extensions to convert to an IEnumerable, and then you can use Select on that. Hope that helps.


Regex wordMatcher = new Regex(@"\p{L}+");
return wordMatcher.Matches(text).Cast<Match>().Select(c => c.Value);

Regex wordMatcher = new Regex(@"\p{L}+");
return wordMatcher.Matches(text).OfType<Match>().Select(c => c.Value);

Using Regex for Text Manipulation in Python, The method str.match(regexp) finds matches for regexp in the string str. It has 3 modes: If the regexp doesn’t have flag g , then it returns the first match as an array with capturing groups and properties index (position of the match), input (input string, equals str ):

In Java, I am trying to return all regex matches to an array but it seems that you can only check whether the pattern matches something or not (boolean). How can I use a regex match to form an array of all string matching a regex expression in a given string?

I am running through lines in a text file using a python script. I want to search for an img tag within the text document and return the tag as text.. When I run the regex re.match(line) it returns a _sre.SRE_MATCH object.

Method : Using join regex + loop + re.match() This task can be performed using combination of above functions. In this, we create a new regex string by joining all the regex list and then match the string against it to check for match using match() with any of the element of regex list.

  • This previous answer may help:…
  • did try that but i always get foreach statement cannot operate on variables of type 'System.Text.RegularExpressions.Match' because 'System.Text.RegularExpressions.Match' does not contain a public definition for 'GetEnumerator'
  • to retain multiple groups, see my answer below
  • The result of this isn't of "List" type. However, if you change the last row to .Select(c => c.Value)).ToList<string>(); then it will be.
  • @Cragmonkey right; but you shouldn't need to specify the type, just .ToList() (.net45)
  • Threw that in there bc I got a type exception without it.
  • Nice shot. I love the .Skip(1) section.