简体   繁体   中英

Creating a regular grammar out of a regular expression

Could anyone please step me through the process of obtaining a regular grammar from a regular expression? I found few 'tutorials', but I am still unable to turn a more complicated regular expression into a grammar.

How would you tackle ((a+b)*(c|d))+a? ?

I though of

A -> aB
A -> aA
B -> bA
A -> cC
A -> dC
C -> cA
C -> dA
C -> a
C -> epsilon

But it's obviously incorrect.

Just work from inside out. Each operator introduces a new non-terminal

 Operator  Grammar     Operator  Grammar
 --------  -------     --------  -------
    R|S     A->R          R*      A->
            A->S                  A->AR

    R?      A->           R+      A->R
            A->R                  A->AR

(Most expositions will also introduce new nonterminals for concatenation; here, I didn't bother. I hope it's not confusing.)

Example:

((a+b)*(c|d))+a?

Sub-          Rewritten with   Rules for
expression    new nonterminal  new nonterminal
----------    ---------------  -----------
a+            A                A->a    A->Aa
a+b           Ab
(a+b)*        (Ab)*            B->     B->BAb
c|d           C                C->c    C->d
(a+b)*(c|d)   BC
(a+b)*(c|d)+  (BC)+            D->BC   D->DBC
a?            E                E->     E->a
(a+b)*(c|d)+  DE               S->DE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM