Is there a way to create a string that matches a given C# regex?

Posted by Chris Phillips on Stack Overflow See other posts from Stack Overflow or by Chris Phillips
Published on 2011-03-10T00:07:11Z Indexed on 2011/03/10 0:10 UTC
Read the original article Hit count: 138

Filed under:
|

My application has a feature that parses text using a regular expression to extract special values. I find myself also needing to create strings that follow the same format. Is there a way to use the already defined regular expression to create those strings?

For example, assume my regex looks something like this:

public static Regex MyRegex = new Regex( @"sometext_(?<group1>\d*)" );

I'd like to be able to use MyRegex to create a new string, something like:

var created = MyRegex.ToString( new Dictionary<string, string>() {{ "group1", "data1" }};

Such that created would then have the value "sometextdata1".

© Stack Overflow or respective owner

Related posts about c#

Related posts about regex