简体   繁体   English

如何在OCaml中使用“匹配”和正则表达式匹配字符串?

[英]How can I match strings using “match with” and regex in OCaml?

My OCaml .ml code looks like this: 我的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)

Why does the above code not work? 为什么上面的代码不起作用? How can I get it to work? 我怎样才能让它发挥作用?

EDIT: 编辑:

I don't need to do a lot of parsing. 我不需要做很多解析。 So, I want it to remain in a OCaml .ml file and not a OCamllex file 所以,我希望它保留在OCaml .ml文件而不是OCamllex文件中

The match keyword works with OCaml patterns. match关键字与OCaml模式一起使用。 A regex isn't an OCaml pattern, it's a different kind of pattern, so you don't use match for them. 正则表达式不是OCaml模式,它是一种不同的模式,因此您不要使用match

In the same Str module with the regexp function are the matching functions. 在具有regexp功能的相同Str模块中是匹配函数。

If you have a lot of regular expression matching to do, you can use ocamllex , which reads a file of definitions similar to your (unfortunately invalid) definition of idregex , and generates OCaml code to do the matching. 如果要进行大量的正则表达式匹配,可以使用ocamllex ,它读取类似于idregex (不幸的无效)定义的定义idregex ,并生成OCaml代码以进行匹配。

Here's a session showing how to do a simple match of your pattern using the Str module. 这是一个会话,展示了如何使用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

As a side comment, your code doesn't really look anything like OCaml. 作为旁注,您的代码看起来并不像OCaml。 It looks something like a mix of OCaml and ocamllex. 它看起来像是OCaml和ocamllex的混合物。 There actually is a system a little bit like this called micmatch . 实际上有一个类似于micmatch的系统 It seems you're planning to use the stock OCaml language (which I applaud), but it might be interesting to look at micmatch at some point. 看来你正计划使用库存OCaml语言(我鼓掌),但在某些时候看看micmatch可能会很有趣。

Does the following work and do what you want? 以下工作并做你想做的事吗?

open Str

let evalT (x, y) =
  let idexp = "[a-zA-Z]+ [a-zA-Z0-9_]*" in
  let full_idexp = "^Id(" ^ idexp ^ ")$" in
  let id_match x = string_match (regexp full_idexp) x 0 in
  if id_match x then Some (x, y) else None;;

I'm an OCaml noob, but your code doesn't look like OCaml at all. 我是OCaml noob,但你的代码根本不像OCaml。 I see that your question is very old, but it still comes up high enough on some searches, so I figured it might help someone else if not the OP. 我看到你的问题很老了,但是在一些搜索中它仍然足够高,所以我认为如果不是OP,它可能对其他人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM