Cristi Băluță
Cristi Băluță

Reputation: 1305

Troubles with ocaml regexp, basic patterns don't work

I have this regex which works:

Str.string_match (Str.regexp "[0-9][0-9][0-9][0-9]\\.[0-9][0-9]\\.[0-9][0-9]") dir 0

But I want to simplify it and it simply doesn't work

"\\d{4}\\.\\d{2}\\.\\d{2}"

There were other attempts to make it work but i came to the conclusion that it has troubles with the d, {} and even with grouping chars with () This patterns work in any other language and are used even in this huge list of examples http://pleac.sourceforge.net/pleac_ocaml/patternmatching.html

Any ideas? Thanks

Upvotes: 2

Views: 295

Answers (2)

user2299816
user2299816

Reputation:

You can use a different library that supports the "\d" syntax, like ocaml-re (which is written in pure OCaml and supports multiple regex syntaxes, including POSIX and a subset of PCRE).

For example:

$ opam install re

$ ocaml
# #use "topfind";;
# #require "re.pcre";;
# let re = Re_pcre.regexp "\\d{4}\\.\\d{2}\\.\\d{2}";;
# Re.execp re "1234.01.243";;
- : bool = true
# Re.execp re "1234.501.24";;
- : bool = false

Upvotes: 1

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66803

If you look at the documentation of the Str module you'll find that Perl-style notations like \d are not supported.

There is a Perl-Compatible Regular Expression library.

Upvotes: 4

Related Questions