1

因此,如果我有简单的正则表达式,例如:

"g{1,3}(a|e|i|o|u)"

我希望我的程序生成字符串

ga
ge
gi
go
gu
gga
gge
ggi
ggo
ggu
ggga
ggge
gggi
gggo
gggu

我不会将“g *(a | e | i | o | u)”用于正则表达式,因为可以有无限数量的'g'并且会有无限数量的字符串。

对简单有效的算法有什么建议吗?我想我将能够通过使用 for/while 循环以蛮力的方式制作这些字符串,但我想知道是否有任何方法可以让这个算法工作。

我用谷歌搜索了如何从正则表达式创建字符串,许多人似乎重定向到: https ://code.google.com/p/xeger/ 以使用已构建的库,但我想知道是否可以获得一些建议我自己的这些简单的正则表达式。

4

3 回答 3

1

Xeger 是开源的。您可以浏览他们的代码库以获取想法。

编辑:

他们的代码库看起来很小,所以不应该太难。它只生成将匹配的随机字符串,而不是所有字符串。不过,这仍然是一个很好的起点。

于 2013-03-28T18:47:16.797 回答
1

我创建了Debuggex,它生成随机字符串,让您了解正则表达式的作用。

如果您的正则表达式已经有了解析树,则可以使用以下逻辑生成随机匹配:

OrTree.random:
    Choose a child randomly, return its random()

ConcatTree.random:
    For every child, call random()
    Return the concatenation of all the results

RepeatTree.random:
    Choose a valid random number of repetitions within min and max
    Call random() on your child that many times
    Return the concatenation of all the results

Literal.random:
    Return the literal

即使使用*运算符,也可以生成随机字符串。这是通过选择从 0 到无穷大的分布来生成数字来完成的,就像您对有限集使用均匀分布一样。例如:

InfiniteRepeatTree.random:
    Flip a coin until I get tails
    Call random on child() the number of times that the coin landed heads
    Return concatenation of the results

希望有帮助:)

于 2013-03-28T18:53:58.733 回答
0
char[] vowels = new char[] {'a','e','i','o','u'};
for (int i = 1; i <= 3; i++) {
    for (int j = 0; j < vowels.length; j++) {
         for (int k = 0; k < i; k++) {
             System.out.print("g");
         }
         System.out.println(vowels[j]);
    }
}

不是通用解决方案,但它适用于您的具体示例

于 2013-03-28T18:48:04.067 回答