Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I match strings using "match with" and regex in OCaml?

My OCaml .ml code looks like this:

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

like image 828
P.C. Avatar asked Aug 09 '14 17:08

P.C.


1 Answers

The match keyword works with OCaml patterns. A regex isn't an OCaml pattern, it's a different kind of pattern, so you don't use match for them.

In the same Str module with the regexp function are the matching functions.

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.

Here's a session showing how to do a simple match of your pattern using the Str module.

$ 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. It looks something like a mix of OCaml and ocamllex. There actually is a system a little bit like this called 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.

like image 158
Jeffrey Scofield Avatar answered Oct 02 '22 05:10

Jeffrey Scofield