我如何知道何时在正则表达式解析树中插入串联节点?

时间:2012-04-28 06:47:09

标签: regex parsing haskell

我正在开发一个有趣的项目,涉及从正则表达式生成一个解析树。我已经完成了大部分工作,但我对如何集成连接感到兴奋。

*Main> :l regex.hs 
[1 of 1] Compiling Main             ( regex.hs, interpreted )
Ok, modules loaded: Main.
*Main> toPostfix "a"
"a"
*Main> toPostfix "a|b"
"ab|"
*Main> toPostfix "((a|b)|c)"
"ab|c|"
*Main> toPostfix "((a|b)|c)de"
"ab|c|de"
*Main> toPostfix "((a|b)|c)*de"
"ab|c|*de"
*Main> toPostfix "(ab)*"
"ab*" -- Should be ab&*
*Main> toPostfix "(ab|bc)"
"abbc|" -- Should be ab&bc&|

这是我的代码:

import Data.List
import Control.Monad

data Reg = Epsilon |
           Literal Char |
           Or Reg Reg |
           Concat Reg Reg |
           Star Reg
           deriving Eq


showReg :: Reg -> [Char]
showReg Epsilon        = "@"
showReg (Literal c)    = [c]
showReg (Or r1 r2)     = "(" ++ showReg r1 ++  "|" ++ showReg r2 ++ ")"
showReg (Concat r1 r2)   = "(" ++ showReg r1 ++ showReg r2 ++ ")"
showReg (Star r)       = showReg r ++ "*"


instance Show Reg where
    show = showReg

evalPostfix :: String -> Reg 
evalPostfix = head . foldl comb []
    where
        comb :: [Reg] -> Char -> [Reg]
        comb (x:y:ys) '|'   = (Or y x) : ys
        comb (x:y:ys) '&'   = (Concat y x) : ys
        comb (x:xs) '*'     = (Star x) : xs
        comb xs '@'         = Epsilon : xs
        comb xs s           = (Literal s) : xs


-- Apply the shunting-yard algorithm to turn an infix expression
-- into a postfix expression.
shunt :: String -> String -> String -> String
shunt o p [] = (reverse o) ++ p
shunt o [] (x:xs)
    | x == '(' = shunt o [x] xs
    | x == '|' = shunt o [x] xs
    | otherwise = shunt (x:o) [] xs
shunt o (p:ps) (x:xs)
    | x == '(' = shunt o (x:p:ps) xs
    | x == ')' = case (span (/= '(') (p:ps)) of
        (as, b:bs) -> shunt (as ++ o) bs xs
    | x == '|' = case (p) of
        '(' -> shunt o (x:p:ps) xs
        otherwise -> shunt (p:o) (x:ps) xs
    | x == '*' = shunt (x:o) (p:ps) xs
    | otherwise = shunt (x:o) (p:ps) xs


-- | Convert an infix expression to postfix
toPostfix :: String -> String
toPostfix = shunt [] []


-- | Evaluate an infix expression
eval :: String -> Reg
eval = evalPostfix . toPostfix

特别是,分流功能正在完成所有繁重的工作,并且应该进行改变。 (树可以很容易地在evalPostfix中构建。)

现在,我花了最后几个小时寻找解释如何做到这一点的教程,但没有任何运气。我想说我需要跟踪我有多少悬挂式表达式,如果我会做任何可以创建三个的东西,插入一个'&',但这似乎效率低下而且我确定有一个更好的办法。如果有人能看到如何对代码进行更改或者可以指出我正确的方向,我将非常感激。

1 个答案:

答案 0 :(得分:3)

分流码算法主要用于处理将中缀运算符转换为后缀运算符。这两个复杂情况是正则表达式语法已经有一个后缀运算符*,并且中缀连接运算符是隐式的。这些组合使解析变得烦人。

" abcd"看看中缀&?它是& b& c& d。这应该是后缀ab& c& d&或abcd&&&amp ;?第一个是左关联,第二个是右关联。我声称第二个更适合解析正则表达式。

现在,a,b,c或d中的每一个都可能是括号中的正则表达式,并且每个可能后跟一个' *'。

我会看到有关增强代码以添加& ...

的信息

更新:您的代码错误

*Main> toPostfix' "a|bcd"
"abcd|"

我无法轻易修复错误并将其扩展为添加&,所以我现在就放弃了。