ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetMatchValue

Returns a collection of string that matched on the pattern.

Source

public static class RegexHelper
{
    public static IEnumerable<string> GetMatchValue(this string rawString, string pattern, bool uniqueOnly = false)
    {
        MatchCollection matches = Regex.Matches(rawString, pattern, RegexOptions.IgnoreCase);
        IEnumerable<string> result = matches.Cast<Match>().Select(m => m.Value);
        if (uniqueOnly) return result.Distinct().ToList<string>();

        return result.ToList<string>();
    }
}

Example

[TestClass]
public class RegexHelperTest
{
    [TestMethod]
    public void GetRegexMatches()
    {
        const string input = "the quick big brown fox jumps over the lazy dog";
        const string pattern = @"\b[a-zA-z]{3}\b";      // find three-letter words
        const int expectedMatched = 5;                  // the, big, fox, the, dog

        IEnumerable<string> result = input.GetMatchValue(pattern);

        Assert.AreEqual(result.Count(), expectedMatched);
    }

    [TestMethod]
    public void GetRegexUniqueMatches()
    {
        const string input = "the quick big brown fox jumps over the lazy dog";
        const string pattern = @"\b[a-zA-z]{3}\b";      // find three-letter words
        const int expectedMatched = 4;                  // the, big, fox, dog

        IEnumerable<string> result = input.GetMatchValue(pattern, true);

        Assert.AreEqual(result.Count(), expectedMatched);
    }
}

Author: Totet

Submitted on: 1 apr. 2015

Language: C#

Type: String

Views: 4201