regex - 如何生成与 Julia 中的正则表达式匹配的随机字符串?

标签 regex julia

相关问题:

  • Random string that matches a regexp
  • How to generate random alphanumeric string in julia?

  • 这个问题相当简单。我发现了许多其他语言的替代品,但在 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) 的地方应该更加小心。 .
    由于最终状态仍然可以有输出边,我选择以统一的概率处理停止和每个边。我认为这可能会导致潜在的无限项要么很短要么很长;谷歌“玻尔兹曼采样器”如何解决这个问题(不要与玻尔兹曼分布的采样混淆!),但该解决方案涉及数学问题。
    或者,您可以使用 ccallPyCall调用 rxvm_gen Rxvm.gen librxvm ,其中包含(可能)非常高效的非回溯正则表达式代码。

    关于regex - 如何生成与 Julia 中的正则表达式匹配的随机字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021343/

    相关文章:

    regex - 基于本体的字符串分类

    python - 正则表达式:如果后面跟着一组运算符,如何捕获括号组?

    javascript - 如何使用正则表达式抓取 URL 内容

    json - Julia 中的 API POST 请求

    julia - 类似于 'SubArray' 但有多个父数组?

    python - 从 python 正则表达式中提取两个值

    c# - 用双反斜杠替换反斜杠、正斜杠和双正斜杠

    arrays - 在 Julia 中将 Vector 转换为 Matrix 的最佳方法?

    julia - 日译英

    for-loop - 在 julia 中将两个嵌套的 for 循环合并为一个 for 循环