Convert finite state machine to regular expression

后端 未结 5 511
面向向阳花
面向向阳花 2021-01-31 22:14

Is there a tool (or an algorithm) to convert a finite state machine into a regular expression?

(not the other way around, that would be easy).

5条回答
  •  广开言路
    2021-01-31 23:13

    I believe the best tool I have used is greenery. It is a FSM/regex conversion library for python. You can read more about the library here and the algorithm used is well described here.


    Example

    The model that can be found on the website can be converted like this:

    from greenery import fsm, lego
    
    A, B, C, D, E = range(5)
    a, b = 'a', 'b'
    
    # create the FSM
    machine = fsm.fsm(
        alphabet = {a, b},
        states   = {A, B, C, D, E},
        initial  = A,
        finals   = {C, E},
        map      = {
                A : {a: B, b: D},
                B : {a: C, b: E},
                C : {a: C, b: E},
                D : {a: B, b: D},
                E : {a: B, b: D}
        },
    )
    
    # convert it to regex
    rex = lego.from_fsm(machine)
    

    The output is the following:

    >>> print(machine)
    
      name final? a b
    ------------------
    * 0    False  1 3
      1    False  2 4
      2    True   2 4
      3    False  1 3
      4    True   1 3
    
    >>> print(rex)
    
    b*a((a*(a|b+))?ba)*(a+b?|b)
    

    Note

    The version on PYPI has some problem with assertions, and the github version has some problems with the memory, but the combination python 3.x + github version is awesome.

提交回复
热议问题