alifirat
alifirat

Reputation: 2927

Ocaml - regexp matching words separated by comma doesn't work

I try to know is a string is well formed as a string separated by comma like "foo,bar,bang" and a string like "foo," should be not matched.

I don't understand why my regexp doesn't work on the following example :

#load "str.cma"

let regexp = Str.regexp "[a-ZA-Z0-9]+(,[a-ZA-Z0-9]+)*"
let str = "foo,bar,bang"  
let s = Str.string_match regexp str 0 

My regex seems good but the returning result by the last line is false. Where am I wrong ?

Upvotes: 2

Views: 3434

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

The parentheses ( ... ) match actual parentheses in OCaml regular expressions. To get grouping parentheses you need to use \( ... \).

So, the following should work:

#load "str.cma";;

let regexp = Str.regexp "[a-zA-Z0-9]+\\(,[a-zA-Z0-9]+\\)*"
let str = "foo,bar,bang"  
let s = Str.string_match regexp str 0;;

Notes:

  • Need to escape \ in a string constant, hence \\( ... \\)
  • I fixed your a-z ranges

Upvotes: 2

Related Questions