如何在OCaml中将字符串解析为正则表达式类型

Jac*_*ale 1 regex ocaml

我们定义一个这样的正则表达式:

type regex_t =
    | Empty_String
    | Char of char
    | Union of regex_t * regex_t 
    | Concat of regex_t * regex_t 
    | Star of regex_t 
Run Code Online (Sandbox Code Playgroud)

我们想写一个函数string_to_regex: string -> regex_t.

  • 唯一的焦点Empty_string是'E'
  • 唯一的字符Char是'a'..'z'
  • '|' 是为了Union
  • '*'代表 Star
  • Concat 假设用于连续解析.
  • '('/')'具有最高的优先权,然后是明星,然后是concat,然后是联盟

例如,

(a|E)*(a|b) 将会

Concat(Star(Union(Char 'a',Empty_String)),Union(Char 'a',Char 'b'))
Run Code Online (Sandbox Code Playgroud)

如何实施string_to_regex

Tho*_*ash 5

Ocamllex和menhir是编写词法分析器和解析器的绝佳工具

ast.mli

type regex_t =
| Empty
| Char of char
| Concat of regex_t * regex_t
| Choice of regex_t * regex_t
| Star of regex_t
Run Code Online (Sandbox Code Playgroud)

lexer.mll

{ open Parser }

rule token = parse
| ['a'-'z'] as c { CHAR c }
| 'E' { EMPTY }
| '*' { STAR }
| '|' { CHOICE }
| '(' { LPAR }
| ')' { RPAR }
| eof { EOF }
Run Code Online (Sandbox Code Playgroud)

parser.mly

%{ open Ast %}

%token <char> CHAR
%token EMPTY STAR CHOICE LPAR RPAR CONCAT
%token EOF

%nonassoc LPAR EMPTY CHAR

%left CHOICE
%left STAR
%left CONCAT

%start main
%type <Ast.regex_t> main

%%

main: r = regex EOF { r }

regex:
| EMPTY { Empty }
| c = CHAR { Char c }
| LPAR r = regex RPAR { r }
| a = regex CHOICE b = regex { Choice(a, b) }
| r = regex STAR { Star r }
| a = regex b = regex { Concat(a, b) } %prec CONCAT
Run Code Online (Sandbox Code Playgroud)

main.ml

open Ast

let rec format_regex = function
| Empty -> "Empty"
| Char c -> "Char " ^ String.make 1 c
| Concat(a, b) -> "Concat("^format_regex a^", "^format_regex b^")"
| Choice(a, b) -> "Choice("^format_regex a^", "^format_regex b^")"
| Star(a) -> "Star("^format_regex a^")"

let () =
  let s = read_line () in
  let r = Parser.main Lexer.token (Lexing.from_string s) in
  print_endline (format_regex r)
Run Code Online (Sandbox Code Playgroud)

并编译

ocamllex lexer.mll
menhir parser.mly
ocamlc -c ast.mli
ocamlc -c parser.mli
ocamlc -c parser.ml
ocamlc -c lexer.ml
ocamlc -c main.ml
ocamlc -o regex parser.cmo lexer.cmo main.cmo
Run Code Online (Sandbox Code Playgroud)

然后

$ ./regex
(a|E)*(a|b)
Concat(Star(Choice(Char a, Empty)), Choice(Char a, Char b))
Run Code Online (Sandbox Code Playgroud)