正则表达式与自动机

Regular Expression

A regular expression is a notation to specify a set (possibly infinite) of strings.

正则表达式是解决 pattern matching 问题的有力武器。与 substring search 问题不同,pattern matching 问题要求在文本中找到所有匹配给定 pattern 的字符串集合,而不是某个单独的精确匹配的子串。

正则表达式的基本 operations 有四种,按优先级从大到小分别是 :

  • parentheses. ex. (AB)*A
  • closure. ex. AB*A
  • concatenation. ex. ABA
  • or. ex. AA | ABA

此外还有几个约定俗成的 additional operations,比如:

  • wildcard. ex. .U.U.U.
  • character class. ex. [A-Za-z][a-z]*
  • at least 11. ex. A(BC)+DE
  • exactly kk. ex. [0-9]{5}-[0-9]{4}

教授在这一节的末尾对正则表达式做了一个很精准的总结:"REs are amazingly powerful and expressive, but using them in applications can be amazingly complex and error-prone."

Nondeterministic Finite-State Automata

在介绍 KMP 算法时,我们引入了 DFA(deterministic finite-state automata, 确定性有限状态自动机)的概念并以此为基础构造了 KMP 自动机。类似的,对于 RE 我们也能构建对应的 DFA。根据 Kleene's theorem 有:

  • For any DFA, there exists a RE that describes the same set of strings.
  • For any RE, there exists a DFA that recognizes the same set of strings.

因此,我们能够提出用 RE 实现 pattern matching 的 basic plan:

  • Build DFA from RE.
  • Simulate DFA with text as input. Pattern matched if it reaches the halting state.

然而,理想很美好,现实很残酷,basic plan 实际上是 infeasible 的。这是因为我们构建的 DFA may have exponential number of states. 例如给出的 pattern 为 a.......,每多一个 wildcard,DFA 的状态数就将增加 RR 倍;有 nn 个 wildcard 的 RE 所构建的 DFA 将具有至少 RnR^n 个状态。

为了解决这个问题,NFA(nondeterministic finite-state automata,非确定性有限状态自动机)横空出世。不得不说这真的是一个非常天才的想法。我们构造 Regular-expression-matching NFA 如下:

  • We assume RE enclosed in parentheses.
  • One state pre RE character (start = 0, accept = M).
  • Red ε\varepsilon-transition only changes state, but do not scan text.
  • Black match transition changes state and scan to next text char.
  • Accept if any sequence of transitions ends in accept state.

NFA corresponding to the pattern ( ( A*B | AC ) D )

可以看到,NFA 中的状态数只与 RE 的长度有关;并且它巧妙地将 transitions 分为两种,红色的 ε\varepsilon 转移与黑色的 match 转移。其中,利用 ε\varepsilon 转移可以在不读入字符的前提下转移到新的状态。

这一设计虽然天才,但是也同时带来了不确定性(nondeterminism)。与 DFA 中 sequence 作为一个确定的 “解” 不同,NFA 中的 sequence 更像是:

  • One view: machine can guess the proper sequence of state transitions.
  • Another view: sequence is a proof that machine accepts the text.

AAAABD sequence matched by the above NFA

可以看到,NFA 中存在若干个 applicable transitions,因此 NFA simulation 远比 DFA simulation 更加 tricky: we need to systematically consider all possible transition sequences.

NFA Simulation

在理解了 NFA 的原理之后,其 simulation 也变得十分简单。我们利用类似多源 BFS 的思路模拟每一步能够到达的状态的集合(“一步”代表读入一个 text character)。具体实现上,我们:

  • State names. Integers from 00 to MM (number of symbols in RE).
  • Match-transitions. Keep regular expression in array re[].
  • ε\varepsilon-transitions. Store in a diagraph GG.
  • Simulation. Maintain set of all possible (reachable) states that NFA could be in after reading in the first ii text characters. 其中 reachable states 用 DFS 即可找到。

One step in simulating an NFA

Determining whether an NN-character text is recognized by the NFA corresponding to an MM-character pattern takes time proportional to MNMN in the worst case.

java
public class NFA {
    private char[] re;    // match transitions
    private Digraph G;    // epsilon-transition digraph
    private int M;        // number of states
    
    public NFA(String regexp) {
        M  = regexp.length();
        re = regexp.toCharArray();
        G  = buildEpsilonTransitionDigraph();
    }
    
    public boolean recognizes(String txt) {
        Bag<Integer> pc = new Bag<Integer>();
        DirectedDFS dfs = new DirectedDFS(G, 0);
        for (int v = 0; v < G.V(); ++v)
            if (dfs.marked(v))	pc.add(v);
        
        for (int i = 0; i < txt.length(); ++i) {
            Bag<Integer> states = new Bag<Integer>();
            for (int v : pc) {
                // not necessarily a match since RE needs to match full text
                if (v == M)	continue;  
                if ((re[v] == txt.charAt(i)) || re[v] == '.')  // follow match transitions
                    states.add(v+1);
            }
            dfs = new DirectedDFS(G, states);    // follow epsilon-transitions
            pc = new Bag<Integer>();
            for (int v = 0; v < G.V(); ++v)
                if (dfs.marked(v))	pc.add(v);
        }
    }
    
    public Digraph buildEpsilonTransitionDigraph() {
        /* stay tuned */
    }
}

NFA Construction

NFA construction 本质上是图的构建,而图的形式是由 RE 对各种 operations 的定义决定的。这里将着重介绍 RE 中四种基本 operations 的连边方式。(slide 54RegularExpressions.pdf 上有对应的实例图,很清晰)

  • Concatenation. Add match-transition edge from state corresponding to characters to next state.
  • Parentheses. Add a ε\varepsilon-transition edge from parentheses to next state.
  • Closure. Add three ε\varepsilon-transition edges for each * operator.
    • character/closure expression to *.
    • * to characte/closure expression.
    • * to next state.
  • Or. Add two ε\varepsilon-transition edges for each | operator.

可以发现 or 操作一定是与 parentheses 伴生的,且只有在右括号的位置确定后才能确定如何连边,因此用栈来维护是一个很自然的想法。

Proposition. Building the NFA corresponding to an MM-character regular expresssion takes time and space proportional to MM.

对于长度为 MM 的RE 中的每个字符,我们最多执行三次连边操作与两次栈操作,可以视为 constant-time。

java
private Digraph buildEpsilonTransitionDigraph() {
    Digraph G = new Digraph(M+1);
    Stack<Integer> ops = new Stack<Integer>();
    for (int i = 0; i < M; ++i) {
        int lp = i;
        
        if (re[i] == '(' || re[i] == '|') ops.push(i);    // left parentheses and |
        else if (re[i] == ')') {
            int or = ops.pop();
            if (re[or] == '|') {                          // 2-way or
                lp = ops.pop();
                G.addEdge(lp, or+1);
                G.addEdge(or, i);
            }
            else lp = or;
        }
        if (i < M-1 && re[i+1] == '*') {                  // closure
            G.addEdge(lp, i+1);
            G.addEdge(i+1, lp);
        }
        
        if (re[i] == '(' || re[i] == '*' || re[i] == ')') // metasymbols
            G.addEdge(i, i+1);
    }
    return G;
}

Regex Miscellaneous

Generalized RE Print

Generalized/Global regular expression print(grep, 全局正则表达式打印)我们应该再熟悉不过了。在学习了 RE NFA 的 simulation 与 construction 之后,我们也能自己实现 grep。

java
public class GREP {
    public static void main(String[] args) {
        String re = "(.*" + args[0] + ".*)";    // contains RE as a substring
        NFA nfa = new NFA(re);
        while (StdIn.hasNextLine()) {
            String line = StdIn.readLine();
            if (nfa.recognized(line))
                StdOut.println(line);
        }
    }
}

grep 的最坏时间复杂度与 substring search 问题的 brute-force 算法相同,均是 ∼MN\sim MN;但 pattern matching 问题确实要比 substring search 更加 fundamental。

Not-So-Regular Expressions

正则表达式能描述特定的字符串集合(pattern),那么是否所有的 pattern 都能被正则表达式表示呢?答案是否定的。举几个非正则(non-regular)pattern 的例子:

  • String of the form wwww for some string ww: beriberi.
  • Unary strings with a composite number of 1s: 111111, 1111, 11...
  • Bitstrings with an equal number of 0s and 1s: 01110100.
  • Palindromes. abccba.

还有一个许多编程语言中支持的 RE additional operation, back-references: \1 notation matches subexpression that was matched earlier. 但实际上,这一 feature 将会令 pattern matching 问题变得 intractable。

Abstract Machines

Abstract machines, languages, and nondeterminism.

  • Basis of the theory of computation.
  • Basis of programming languages.

实际上我们熟悉的 compiler 本质上与 DFA,NFA 这些 abstract machines 没有区别:它们都将某种“程序”(program)翻译成另一种“机器码”(machine code),再由 executor(即 simulator)进行执行。

  • KMP: string => DFA => DFA simulator.
  • grep: RE =? NFA => NFA simulator.
  • javac: Java language => Java byte code => JVM.
CC BY-NC-SA 4.0
正在加载评论…