我想知道是否有软件可以根据给定的正则表达式和其他限制条件(例如长度),生成始终匹配给定正则表达式的随机文本。
谢谢
是的,可以生成与正则表达式随机匹配的软件:
Xeger 可以完成这个任务:
String regex = "[ab]{4,6}c";
Xeger generator = new Xeger(regex);
String result = generator.generate();
assert result.matches(regex);
虽然有些晚了,但这可能对新手有所帮助。这是一个有用的Java库,提供了许多功能来使用正则表达式生成字符串(随机生成、基于索引生成字符串、生成所有字符串等)。在这里查看。
例子:
Generex generex = new Generex("[0-3]([a-c]|[e-g]{1,2})");
// generate the second String in lexicographical order that match the given Regex.
String secondString = generex.getMatchedString(2);
System.out.println(secondString);// it print '0b'
// Generate all String that matches the given Regex.
List<String> matchedStrs = generex.getAllMatchedStrings();
// Using Generex iterator
Iterator iterator = generex.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
// it print 0a 0b 0c 0e 0ee 0e 0e 0f 0fe 0f 0f 0g 0ge 0g 0g 1a 1b 1c 1e
// 1ee 1e 1e 1f 1fe 1f 1f 1g 1ge 1g 1g 2a 2b 2c 2e 2ee 2e 2e 2f 2fe 2f 2f 2g
// 2ge 2g 2g 3a 3b 3c 3e 3ee 3e 3e 3f 3fe 3f 3f 3g 3ge 3g 3g 1ee
// Generate random String
String randomStr = generex.random();
System.out.println(randomStr);// a random value from the previous String list
def generate_problem(level):
keep_trying = True
while(keep_trying):
regex = gen_regex(level)
# print 'regex = ' + regex
counter = 0
match = 0
notmatch = 0
goodwords = []
badwords = []
num_words = 2 + level * 3
if num_words > 18:
num_words = 18
max_word_length = level + 4
while (counter < 10000) and ((match < num_words) or (notmatch < num_words)):
counter += 1
rand_word = words[random.randint(0,max_word)]
if len(rand_word) > max_word_length:
continue
mo = re.search(regex, rand_word)
if mo:
match += 1
if len(goodwords) < num_words:
goodwords.append(rand_word)
else:
notmatch += 1
if len(badwords) < num_words:
badwords.append(rand_word)
if counter < 10000:
new_prob = problem.problem()
new_prob.title = 'Level ' + str(level)
new_prob.explanation = 'This is a level %d puzzle. ' % level
new_prob.goodwords = goodwords
new_prob.badwords = badwords
new_prob.regex = regex
keep_trying = False
return new_prob
不要从正则表达式开始,而应该考虑编写一个小的上下文无关文法,这将使您能够轻松生成随机文本。不幸的是,我不知道有什么工具可以直接为您做到这一点,因此您需要自己编写一些代码来实际生成文本。如果您之前没有使用过语法,我建议在继续之前阅读一些关于BNF格式和"编译器生成器"的内容...
我不知道有没有现成的,但应该是可行的。通常的方法是编写语法而不是正则表达式,然后为每个非终端创建函数,随机决定要扩展哪个产生式。如果您可以发布要生成的字符串类型的描述以及您使用的语言,我们可能能够帮助您入手。