问题
Is it possible to extract a max length of an allowed string from a regex pattern once it has been loaded into a C# Regex object?
If I have a Regex string defined as @"^[A-Z0-9]{0,20}$", I could use string manipulation to get the maximum allowed length of 20.
However is there a way I can get that more easily, for instance via a Regex object as follows:
var r = new Regex(@"^[A-Z0-9]{0,20}$");
// var max = r.MaxLength;
Update
To set some context, I have an Asp.Net MVC 5 application in which we use a RegexValidationAttribute to provide input validation our view models.
What I would like to do is override that attribute such that I can add a Custom metadata property which contains the maximum allowed length of the string, parsed from the regex string. In my string Editor Template, I will then grab the custom metadata value, and add a maxlength="" attribute to the html <input> tag.
Now I know I could just add a StringLengthAttribute and do it that way, but then I have to remember to keep the regex length and string length in sync. And with more than 1000+ models I want to de-duplicate the effort required.
回答1:
Is it possible to extract a max length of an allowed string from a regex pattern once it has been loaded into a C#
Regexobject?
No. The Regex class have no built-in field/method that does the work.
One could write a method that would try to compute the maximum theoretical length of a match, it would work for simple regexes like the one you mentioned but as soon as multiple alternatives will show up and/or length quantifier (+/*) the calculation of the theoretical max length would be a nightmare.
来源:https://stackoverflow.com/questions/39022278/extract-max-length-of-allowed-string-from-regex-object