P.C*_*.C. 4 regex ocaml ocamllex
我的OCaml .ml代码如下所示:
open Str
let idregex = Str.regexp ['a'-'z' 'A'-'Z']+ ['a'-'z' 'A'-'Z' '0'-'9' '_']*;
let evalT (x,y) = (match x with
Str.regexp "Id(" (idregex as var) ")" -> (x,y)
Run Code Online (Sandbox Code Playgroud)
为什么上面的代码不起作用?我怎样才能让它发挥作用?
编辑:
我不需要做很多解析.所以,我希望它保留在OCaml .ml文件而不是OCamllex文件中
该match关键字适用于OCaml模式.正则表达式不是OCaml模式,它是一种不同的模式,所以你不要使用match它们.
在具有该功能的同一Str模块regexp中是匹配功能.
如果你有很多正则表达式匹配,你可以使用ocamllex,它读取类似于你的(不幸的是无效的)定义的定义文件idregex,并生成OCaml代码来进行匹配.
这是一个会话,展示了如何使用Str模块对模式进行简单匹配.
$ ocaml
OCaml version 4.01.0
# #load "str.cma";;
# let idregex = Str.regexp "[a-zA-Z]+[a-zA-Z0-9_]*";;
val idregex : Str.regexp = <abstr>
# Str.string_match idregex "a_32" 0;;
- : bool = true
# Str.string_match idregex "32" 0;;
- : bool = false
Run Code Online (Sandbox Code Playgroud)
作为旁注,您的代码看起来并不像OCaml.它看起来像是OCaml和ocamllex的混合物.实际上有一个类似于micmatch的系统.看来你正计划使用库存OCaml语言(我鼓掌),但在某些时候看看micmatch可能会很有趣.