See which template created the Regex object?

I have a Regex object created using the new Regex(string pattern) constructor, is there any way later to see which template created the regular expression object?

I cannot access the element of the string "pattern" in Regex or RegexOptions .

Context: the reason I ask, I create several regular expression objects at an early stage during initialization (templates are stored in the configuration file), then they are passed to another class, which will be used often. However, I also need to compare the template string with those stored in the SQL database at runtime.

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

Feel free to offer alternative tips.

+6
source share
2 answers

So, in the debugger hovering over the regular expression object, the template is displayed, so it should be close. Turns off Regex.ToString () returns the template.

ToString : returns the regular expression pattern that was passed to the Regex constructor.

+17
source

It doesn't look like you can do it like this because the Regex.Pattern field Regex.Pattern marked as internal.

You correctly say that it is a good idea to create an object once and reuse it several times, but passing the string as another parameter may be your only option.

If you really want to not do this, you can create a new class that inherits from Regex, and then sets the 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; } } 
+4
source

Source: https://habr.com/ru/post/923212/


All Articles