The regex "\|\|" in OCaml incorrectly matches the string ";;"

Viewed 120

I am using Str.regexp in OCaml to detect double semicolons or or and and symbols among other things, but a lot of the regexes aren't working as intended. For example,

Str.string_match (Str.regexp "\|\|") ";;" 0

returns true. You have to escape a character like '|', so I used "\|\|" as my regex instead of "||". However, I heard you might have to escape twice and write "\\|\\|" in Ocaml, yet this did not work either. So what am I supposed to do? Rubular thinks the Regex should work, but this is Ocaml and not Ruby, so I might've missed some subtle language difference.

2 Answers

There is no (widely accepted) regex standard. And while many common conventions have emerged, every implementation is different. You should therefore always reference the documentation of the implementation you're using.

If you want an implementation that provides more conventional syntax, however, I'd recommend ocaml-re, which is a regex implementation in pure OCaml that offers a choice of several different syntaxes, Perl, Posix and Emacs as well as a subset of PCRE.

It turns out that the regex

"||"

will work. Usually, '|' represents or and needs to be escaped to represent a literal bar, but it seems to be the opposite in Ocaml.

Related