perl生成匹配正则表达式的字符串 [英] perl to generate string to match regex
问题描述
我试图找到一种方法来生成与正则表达式匹配的字符串,例如以下正则表达式:
I try to find a way to generate string that matches regex, for example, the following regex:
[A-Z]{6,6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3,3}){0,1}
我试过了Cpan上的一些perl模块,这些模块不起作用: ->字符串::随机 -> Regexp :: Genex
There are some perl modules on Cpan which I tried that doesn't work: -> String::Random -> Regexp::Genex
不支持String :: Random显示(). Regex :: Genex对此字符串报告错误($ regex).
The String::Random shows () is not supported. Regex::Genex reports error on strings($regex) with this one.
感谢您的帮助!
推荐答案
如果您想要一个通用的解决方案,并且不愿意尝试修复String :: Random,则可以使用
If you want a general solution and you aren't will to work towards fixing String::Random, you could use a large number of monkeys.
use strict;
use warnings qw( all );
use feature qw( say );
my $pattern = qr/^[A-Z]{6}[A-Z2-9][A-NP-Z0-9](?:[A-Z0-9]{3})?\z/;
my $min_len = 0;
my $max_len = 15;
my @syms = map chr, 0x20..0x7E;
my $s;
while (1) {
$s = join '', map { $syms[rand(@syms)] } 1..$min_len+rand($max_len-$min_len+1);
last if $s =~ $pattern;
}
say $s;
此解决方案按字面意义生成完全"随机字符串,直到找到匹配的字符串为止. 这是一种糟糕的方法,而且速度可能很慢.
This solution literally generates "completely" random strings until it find one that matches. It's an awful approach, and it can be quite slow.
您可以通过限制随机字符串生成器(通过$min_len
,$max_len
和@syms
)来加快解决方案的速度.也就是说,您对这些限制越多,此解决方案将支持的模式越少.例如,对于示例模式,使用$min_len = 8; $max_len = 11; @syms = ( 'A'..'Z', '0'..'9' );
会更快,但是使用这些参数可能会阻止它对其他模式起作用.
You can speed it up the solution by restricting the random string generator (via $min_len
, $max_len
and @syms
). That said, the more you restrict these, the fewer patterns this solution will support. For example, using $min_len = 8; $max_len = 11; @syms = ( 'A'..'Z', '0'..'9' );
will be insanely faster for the example pattern, but using those parameters might prevent it from working for other patterns.
还请注意,这种方法会使可能性降低.某些匹配的字符串比其他字符串更可能生成.例如,给定^[A-Z]{1,3}\z
的猴子比AAA
产生A
的可能性高得多.
Also note that this approach skews the odds. Some matching strings are more likely to be generated than others. For example, the monkeys are incredibly more likely to produce A
than AAA
given ^[A-Z]{1,3}\z
.
这篇关于perl生成匹配正则表达式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!