gpt4 book ai didi

regex - 如何在 OCaml 中使用 "match with"和正则表达式匹配字符串?

转载 作者:行者123 更新时间:2023-12-05 01:03:09 26 4
gpt4 key购买 nike

我的 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)

为什么上面的代码不起作用?我怎样才能让它工作?

编辑:

我不需要做很多解析。所以,我希望它保留在 OCaml .ml 文件中,而不是 OCamllex 文件中

最佳答案

match关键字适用于 OCaml 模式。正则表达式不是 OCaml 模式,它是一种不同的模式,所以你不要使用 match为他们。

在同一个 Str moduleregexp函数是匹配函数。

如果你有很多正则表达式匹配要做,你可以使用 ocamllex ,它会读取一个定义文件,该文件类似于您的 idregex 的(不幸的是无效的)定义。 ,并生成 OCaml 代码来进行匹配。

这是一个展示如何使用 Str 对您的模式进行简单匹配的 session 。模块。

$ 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

作为旁注,您的代码看起来并不像 OCaml。它看起来像是 OCaml 和 ocamllex 的混合体。实际上有一个有点像这样的系统,叫做 micmatch .看来您正计划使用常用的 OCaml 语言(我对此表示赞赏),但在某些时候查看 micmatch 可能会很有趣。

关于regex - 如何在 OCaml 中使用 "match with"和正则表达式匹配字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25221226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com