Take the 2-minute tour ×

I have a Regex object created with the new Regex(string pattern) constructor, is there a way afterwards to see what pattern the regex object was created with?

I can't seem to be able to access the "pattern" string member in either the Regex or in RegexOptions objects.

Context: Reason I'm asking is I'm creating a few regex objects early on while initializing (patterns are stored in a config file), they then get passed to a different class to be used frequently. However, I also need to compare the pattern string to those stored in a SQL database at run-time.

I would prefer not having to pass a string with the pattern in addition to the regex object. I also feel that creating the object once at startup is not a bad idea since the regex will be reused hundreds of times?

Feel free to provide alternative advices.

share|improve this question
protected internal string pattern That's really awkward... –  Andre Calil Aug 19 '12 at 2:49
@Andre Calil Hmm.. perhaps they wanted to keep the freedom of modifying the patterns internally for compatibility or optimization purposes. –  mtone Aug 19 '12 at 2:57
add comment

2 Answers

up vote 5 down vote accepted

So, in the debugger hovering the cursor over a regex object was showing the pattern, so it had to be close. Turns out Regex.ToString() returns the pattern.

ToString: Returns the regular expression pattern that was passed into the Regex constructor.

share|improve this answer
Easiest solution. No need to create a whole new class. –  John Davis Aug 19 '12 at 4:01
Ha, brilliant! You might want to mark that as the answer. –  Fabian Tamp Aug 19 '12 at 13:28
add comment

It doesn't seem like you can do it like this, seeing as the Regex.Pattern field is marked internal.

You are correct in saying that it's a good idea to create the object once and reuse it multiple times, but passing the string as another parameter might be your only option.

If you really want to avoid doing that, you could create a new class that inherits from Regex, and then sets a Pattern property in the constructor, as follows:

public class MyRegex : Regex
    public String Pattern {protected set; get;}
    public MyRegex(String Pattern) : Regex(Pattern)
            this.Pattern = Pattern;
share|improve this answer
Thanks for your answer, and I like this suggestion! –  mtone Aug 19 '12 at 2:58
No problem, glad it helped. –  Fabian Tamp Aug 19 '12 at 3:13
add comment

Your Answer


