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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With