The most convenient way to check if a string ends with some text in OCaml?

Hi, I checked on the Internet to find a good way to implement “whether a string ends with a specific text” in OCaml, and I found that manipulating a string in OCaml is not as trivial as I expected, compared to other programming languages ​​like Java .

Here is my OCaml code using Str.regexp to check if the file " .ml " name ends if it is an OCaml script file. It does not work as I expected:

let r = Str.regexp "*\\.ml" in
if (Str.string_match r file 0)
  then
    let _ = print_endline ("Read file: "^full_path) in
    readFile full_path
  else
    print_endline (full_path^" is not an OCaml file")

Please note that readFile is a function written by me to read a file from the constructed full_path. I always got output results like

./utilities/dict.ml is not an OCaml file
./utilities/dict.mli is not an OCaml file
./utilities/error.ml is not an OCaml file
./utilities/error.mli is not an OCaml file

OCaml / ?

+4
2

, . *, :

let r = Str.regexp {|.*\.ml|}

, . , :

let r = Str.regexp ".*\\.ml"

, file.mlx, file.ml.something.else .. , , OCaml,

let r = Str.regexp {|.*\.ml[ily]?$|}

regexp Filename , check_suffix:

let is_ml file = Filename.check_suffix file ".ml"

:

let srcs = [".ml"; ".mli"; ".mly"; ".mll"]
let is_ocaml file = List.exists (Filename.check_suffix file) srcs
+5

, :

  • Glob (, regexp bash )
    , * .
  • Posix ( , )

str.
http://caml.inria.fr/pub/docs/manual-ocaml/libref/Str.html

. : Matches any character except newline * : Matches the preceding expression zero, one or several times

, str . , Str.regexp,

let r = Str.regexp ".*\.ml";;
val r : Str.regexp = <abstr>

Str.string_match r "fuga.ml" 0;;
- : bool = true

Str.string_match r "fugaml" 0;;
- : bool = false

Str.string_match r "piyo/null/fuga.ml" 0;;
- : bool = true

glob,
re.

-, .
, ".ml" .

+2

All Articles