Extract Max Length of allowed string from Regex object

被刻印的时光 ゝ 提交于 2021-01-04 08:37:32

问题


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# Regex object?

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!