[英]How to generate an example of valid input using Regex?
I want to generate an example of a valid input by Regex pattern. 我想通过Regex模式生成一个有效输入的示例。 I'm programming with C# .Net
. 我用C# .Net
编程。 Like this: 像这样:
//this emthod doesn't exists, its an example of funcionality that I want.
Regex.GenerateInputExample("^[0-9]{15}$");
So, this example gives-me a possible value, like 000000000000000
. 所以,这个例子给了我一个可能的值,比如000000000000000
。 How to do this? 这个怎么做?
So, this problem would take some time to solve, since the functionality is not built in. I'll give a general way to solve it: 因此,这个问题需要一些时间来解决,因为功能没有内置。我将给出一般解决方法:
Using an ascii (or unicode) chart find out the character codes that correspond to the characters you are using for your regex (65 =A, 69 = D, etc) 使用ascii(或unicode)图表找出与正在使用的正则表达式所使用的字符相对应的字符代码(65 = A,69 = D等)
Create a random function with those bounds. 使用这些边界创建随机函数。 Multiple bounds would take a little more trickery (AZ =26, 0-9 = 10, so a random number from 0- 35) 多边界将需要更多的诡计(AZ = 26,0-9 = 10,所以从0到35的随机数)
Random random = new Random();
int randomNumber = random.Next(65, 70); // this generates a random number including the bounds of 65-69)
char temp = (char)random;
Next you would take the randomly generated characters and add them together into a string. 接下来,您将获取随机生成的字符并将它们一起添加到字符串中。
int lowerBound = 65, upperBound =69;
int length = 6;
char temp;
int randomNumber;
string result= "";
Random rand = new Random();
for (int a = 0; a <= length; a++)
{
randomNumber = rand.Next(lowerBound, upperBound);
temp = (char)randomNumber;
result = result + temp;
} //result is the indirect regex generated string
Indirectly giving you a regex generated string. 间接给你一个正则表达式生成的字符串。
The next step is parsing information out of a regex. 下一步是从正则表达式中解析信息。 I've provided a simple case below that will not work for every regex, due to regex complexity. 由于正则表达式的复杂性,我在下面提供了一个简单的案例,不适用于每个正则表达式。
Regex bob = new Regex("[A-Z]");
int lowerBound = Convert.ToInt32(bob.ToString()[1]);
int upperBound = Convert.ToInt32(bob.ToString()[3]);
int length = 6; //length of the string to be generated
char temp;
int randomNumber;
string result= "";
Random rand = new Random();
for (int a = 0; a <= length; a++)
{
randomNumber = rand.Next(lowerBound, upperBound);
temp = (char)randomNumber;
result = result + temp;
}
( This process could be streamlined into class and utilized etc) (这个过程可以简化为课程并使用等)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.