19

Can someone help me in coding an effective substring check in OCaml? Given two strings, check whether the first one contains the second one?

Using the Str module, can we do this?

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
priyanka
  • 923
  • 1
  • 9
  • 20

2 Answers2

16

Something like this might work:

let contains s1 s2 =
    let re = Str.regexp_string s2
    in
        try ignore (Str.search_forward re s1 0); true
        with Not_found -> false

Here are some tests of the function:

# contains "abcde" "bc";;
- : bool = true
# contains "abcde" "bd";;
- : bool = false
# contains "abcde" "b.";;
- : bool = false
# contains "ab.de" "b.";;
- : bool = true
Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
  • this wont work if `s2` has special regex character sequences in it, like `.`. You'll have to call, `Str.quote s2` first. – nlucaroni Dec 04 '11 at 07:43
  • 1
    I don't think that's true. The purpose of `regexp_string` is to match exactly a particular string. It presumably does quoting internally. My tests show that this code works OK. – Jeffrey Scofield Dec 04 '11 at 07:56
  • 1
    contains is a bad name, cause it has already another meaning in extension libraries. – ygrek Dec 05 '11 at 10:30
  • To use this approach, the `Str` library must be linked: https://v2.ocaml.org/manual/libstr.html or else you get an Error. see: https://stackoverflow.com/questions/3221067/regular-expressions-in-ocaml – marcel fiedler Jul 01 '22 at 05:52
0
let contains_substring search target =
    String.substr_index search target <> None
ESRogs
  • 2,301
  • 2
  • 16
  • 11