Str.
Str.

Reputation: 1439

How to get a complete (eager) match with module Str in OCaml

For hours I am trying to find the right function for this standard problem, example in Tcl shell:

str@suse131-intel:~> tclshi
% regexp -inline {[0-9]+} "I am trying this for the 1001. time!!"
1001
%

I have tried quite a lot, and I can find the start and end of the match, but this can't be it! I only get a minimal match, not an eager match. Am I supposed to pick the match out by hand, so to say? Ocaml interactive:

# let s1 = "this is the 1001. time I am trying this.";;
val s1 : string = "this is the 1001. time I am trying this."
# search_forward (regexp "[0-9]+") s1 0;;
- : int = 12
# group_beginning 0;;
- : int = 12
# group_end 0;;
- : int = 16

Sub question: all these functions referring to the last match ("returns the substring of s that was matched by the last call to one of the following" as the doc says) like matched_string do not look very FP, but exactly the opposite. I this reentrant and task switch save code?

Edit: In my session yesterday I only got one number back. Now I wanted to copy the strange behavoir into this question, but it is working fine. The problem was maybe a mixup of different let definitions.

Complete example:

# #require "str";;
/usr/lib64/ocaml/str.cma: loaded
# open Str;;
# let s1 = "this is the 1001. time I am trying this.";;
val s1 : string = "this is the 1001. time I am trying this."
# search_forward (regexp "[0-9]+") s1 0;;
- : int = 12
# matched_string s1;;
- : string = "1001"

Upvotes: 1

Views: 555

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66803

The OCaml code seems to be matching exactly the same substring as the tcl code, so I'm not sure what extra eagerness you're looking for.

You're right, this interface to string matching is not functional. It depends on hidden state, and is very likely not thread-safe. OCaml Batteries Included has Str.search, which is slightly nicer, and it suggests that the non-FP parts of the interface should be considered obsolescent.

Upvotes: 2

Related Questions