Reputation: 649
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
Upvotes: 5
Views: 9921
Reputation: 1080
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. 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.
Upvotes: 0
Reputation: 66818
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.
Upvotes: 9