REExtract

public static T[ ] REExtract<T>( this string s, string regex )
{
    TypeConverter tc = TypeDescriptor.GetConverter( typeof( T ) );
    if ( !tc.CanConvertFrom( typeof( string ) ) )
    {
        throw new ArgumentException( "Type does not have a TypeConverter from string", "T" );
    }
    if ( !string.IsNullOrEmpty( s ) )
    {
        return 
            Regex.Matches( s, regex )
            .Cast<Match>( )
            .Select( f => f.ToString( ) )
            .Select( f => ( T )tc.ConvertFrom( f ) )
            .ToArray( );
    }
    else
        return new T[ 0 ];
}
Example:
public static int[ ] ExtractInts( this string s )
{
    return s.REExtract<int>( @"\d+" );
}

int[] a = "Some primes: 2, 5, 11, and 17".ExtractInts();
// a == { 2, 5, 11, 17 }

Description

Extracts all fields from a string that match a certain regex. Will convert to desired type through a standard TypeConverter.

Details

Double click on the code to select all.

 

;