14wml
14wml

Reputation: 4166

regex on Ocaml not matching single letter strings, numbers, and spaces?

I want to match commands like

a c x y

where a is the letter "a", c is any letter (a-z, A-Z), and x is a integer and y is an integer (x and y are suppose to coordinates). a, c, x, and y should be seperated by a single space

So I wrote up this regex

string_match (regexp "a [a-zA-z] [0-9]+ [0,9]+") str 0

But when I run it in utop

utop # let str = "a c 7 12";;
val str : string = "a c 7 12"                                                       
utop # string_match (regexp "a [a-zA-z] [0-9]+ [0,9]+") str 0;;
- : bool = false

I get false...

I've also tried regex a[ ][a-zA-z][ ][0-9]+[ ][0,9]+ to match the spaces, but that also hasn't worked

If anyone

Upvotes: 0

Views: 354

Answers (1)

StvnBrkdll
StvnBrkdll

Reputation: 4044

For y, your regex is this: [0,9]. I believe it should be [0-9]. (Note the "," vs. the "-"). [0,9] will match the characters 0, comma, and 9. Your specification says that y is an integer, suggesting that [0-9] is what you want.

So:

a [a-zA-z] [0-9]+ [0-9]+

should work.

Also, consider "anchoring" your regex by beginning it with ^, which matches the beginning of the input, and ending it with $, which matches the end of the input.

So something like this:

^a [a-zA-z] [0-9]+ [0-9]+$

Upvotes: 3

Related Questions