php – 为给定的正则表达式创建所有可能的匹配集

我想知道如何使用有限数量的匹配找到一组给定的正则表达式的所有匹配.

例如:

所有这些例子,你可以假设他们以^开始,以$结尾

`hello?` -> (hell,hello)
`[1-9][0-9]{0,3}` -> (1,2,3 ...,9998,9999)
`My (cat|dog) is awesome!` -> (My cat is awesome!,My dog is awesome!)
`1{1,10}` -> (1,11,...,111111111,1111111111)
`1*` -> //error
`1+` -> //error
`(1|11){2}` -> (1,111,1111) //notice how it doesn't repeat any of the possibilities

如果有一种方法来检索对正则表达式的唯一解决方案,或者有一种方法来确定正则表达式是否具有有限的解决方案,我也会感兴趣.

如果算法可以解析任何正则表达式,那么这将是很好的,但正则表达式的一个强大的子集将是正常的.

我对这个问题的PHP解决方案感兴趣,但其他语言也会很好.

编辑:

我已经在我的正式理论课中学习了大约DFA,可以用来实现正则表达式(和其他常规语言).如果我可以将正则表达式转换为DFA,那么这个解决方案似乎对我来说很直接,但是这种转换对我来说似乎并不棘手.

编辑2:

感谢所有的建议,see my post about the public github project我正在努力“回答”这个问题.

从正则表达式转换为DFA是非常简单的.然而,您将遇到的问题是,生成的DFA可能包含循环(例如,用于*或),这将无法完全扩展.另外,{n,n}无法在DFA中进行干净的表示,因为DFA没有“循环”多少次的“内存”.

这个问题的一个解决方案就是建立一个函数标记和解析正则表达式,然后返回所有可能的匹配的数组.在这里使用递归将帮助你很多.

一个起点,伪码,可能看起来像:

to GenerateSolutionsFor(regex):
    solutions = [""]
    for token in TokenizeRegex(regex):
        if token.isConstantString:
            for sol in solutions: sol.append(token.string)
        else if token.isLeftParen:
            subregex = get content until matching right paren
            subsols = GenerateSolutionsFor(subregex)
            for sol in solutions:
                for subsol in subsols:
                    sol.append(subsol)
        else if token.isverticalBar:
            solutions.add(GenerateSolutionsFor(rest of the regex))
        else if token.isLeftBrace:
            ...

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...