Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matching exact string in Ocaml using regex

Tags:

regex

ocaml

How to find a exact match using regular expression in Ocaml? For example, I have a code like this:

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

where s2 is "_X_1" and s1 feeds strings like "A_1_X_1", "A_1_X_2", ....and so on to the function 'contains'. The aim is to find the exact match when s1 is "A_1_X_1". But the current code finds match even when s1 is "A_1_X_10", "A_1_X_11", "A_1_X_100" etc.

I tried with "[_x_1]", "[_X_1]$" as s2 instead of "_X_1" but does not seem to work. Can somebody suggest what can be wrong?

like image 483
maths-help-seeker Avatar asked Feb 23 '26 15:02

maths-help-seeker


1 Answers

You can use the $ metacharacter to match the end of the line (which, assuming the string doens't contain multiple lines, is the end of the string). But you can't put that through Str.regexp_string; that just escapes the metacharacters. You should first quote the actual substring part, and then append the $, and then make a regexp from that:

let endswith s1 s2 =
  let re = Str.regexp (Str.quote s2 ^ "$")
  in
  try ignore (Str.search_forward re s1 0); true
  with Not_found -> false
like image 127
newacct Avatar answered Feb 25 '26 08:02

newacct