通常在我们的工作中,我们在捕获或匹配操作中使用正则表达式
但是,可以使用正则表达式 – 至少手动 – 来生成与正则表达式匹配的合法句子.当然,一些正则表达式可以匹配无限长的句子,例如表达式. .
在伪代码中,它将运行如下:
re = generate("foo(bar|baz)?",max_match = 100); #Don't give me more than 100 results assert re == ("foobar","foobaz","foo");
什么算法会为我执行此操作?
Microsoft为此提供了基于SMT的免费(MSRL许可)“Rex”工具:
http://research.microsoft.com/en-us/downloads/7f1d87be-f6d9-495d-a699-f12599cea030/
原文链接:https://www.f2er.com/regex/357329.html来自“Rex:符号正则表达式资源管理器”的介绍部分:
We translate (extended) regular expressions or regexes [5] into a symbolic representation of finite automata called SFAs. In an SFA,moves are labeled by formulas representing sets of characters rather than individual characters. An SFA A is translated into a set of (recursive) axioms that describe the acceptance condition for the strings accepted by A and build on the representation of strings as lists.
由于SMT求解器可以在一定大小范围内输出所有可能的解决方案,因此这可能接近您正在寻找的内容.
在更加统计和不太正式的方面,CPAN的Regexp :: Genex模块也可以正常工作:http://search.cpan.org/dist/Regexp-Genex/
您可以使用以下内容:
#!/usr/bin/env perl use Regexp::Genex ':all'; my $hits = 100; my $re = qr/[a-z](123|456)/; local $Regexp::Genex::DEFAULT_LEN = length $re; my %seen; while ((time - $^T) < 2) { @seen{strings($re)} = (); $Regexp::Genex::DEFAULT_LEN++; } print "$_\n" for (sort %seen)[0..$hits-1];
根据需要调整时间和样本大小.希望这可以帮助!