相关问题:
这个问题相当简单。我发现了许多其他语言的替代品,但在 Julia 中没有:
Random Text generator based on regex
还有
Random.randstring
不带Regex
作为论据。
最佳答案
应该可以使用 Automa.jl构建一个 DFA 并随机遍历它。 Automa 使用比 PCRE 更简单的语法,因此您可以用它描述的语言实际上应该是规则的。
我很快将以下内容拼凑起来,主要基于 dot.jl
中的代码:
julia> function rand_re(machine::Automa.Machine)
out = IOBuffer()
node = machine.start
while true
if node.state ∈ machine.final_states
(rand() ≤ 1 / (length(node.edges) + 1)) && break
end
edge, node = rand(node.edges)
label = rand(collect(edge.labels))
print(out, Char(label))
end
return String(take!(out))
end
rand_re (generic function with 1 method)
julia> rand_re(Automa.compile(re"a[0-9][ab]+"))
"a6bbb"
julia> rand_re(Automa.compile(re"a[0-9][ab]+"))
"a9b"
julia> rand_re(Automa.compile(re"a[0-9][ab]+"))
"a3aa"
julia> rand_re(Automa.compile(re"a[0-9][ab]+"))
"a1a"
julia> rand_re(Automa.compile(re"a[0-9][ab]+"))
"a5ba"
需要注意的是,Automa 使用字节编码集作为边缘标签,所以在我写 Char(label)
的地方应该更加小心。 .由于最终状态仍然可以有输出边,我选择以统一的概率处理停止和每个边。我认为这可能会导致潜在的无限项要么很短要么很长;谷歌“玻尔兹曼采样器”如何解决这个问题(不要与玻尔兹曼分布的采样混淆!),但该解决方案涉及数学问题。
或者,您可以使用
ccall
或 PyCall
调用 rxvm_gen
或 Rxvm.gen
的 librxvm
,其中包含(可能)非常高效的非回溯正则表达式代码。
关于regex - 如何生成与 Julia 中的正则表达式匹配的随机字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021343/