Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

safer starts_with function #97

Open
UnixJunkie opened this issue Nov 6, 2012 · 4 comments
Open

safer starts_with function #97

UnixJunkie opened this issue Nov 6, 2012 · 4 comments

Comments

@UnixJunkie
Copy link

It should be like this to be less error prone at use:

(* does the string starts with prefix ? *)
let starts_with ~str ~prfx =
Str.string_match (Str.regexp ("^" ^ prfx)) str 0

@UnixJunkie
Copy link
Author

I think there is even a possible problem in case ~prfx contains some regexp special characters.
The following might be preferable:

(* does the string starts with prefix ? *)
let starts_with ~str ~prfx =
Str.string_match (Str.regexp_string prfx) str 0

@UnixJunkie
Copy link
Author

I am in some other code using this same function, that's why
I notice problems with it (like swapping its parameters inadvertantly or
using mistakenly some special charcters in the ~prfx while you did
not intended them to be compiled in the regexp but matched as-is).

@thelema
Copy link
Owner

thelema commented Nov 6, 2012

On 11/6/2012 1:52 AM, Francois Berenger wrote:

I think there is even a possible problem in case ~prfx contains some
regexp special characters.
The following might be preferable:

(* does the string starts with prefix ? *)
let starts_with ~str ~prfx =
Str.string_match (Str.regexp_string prfx) str 0


Reply to this email directly or view it on GitHub
#97 (comment).

I think this might do unanchored matching; searching for prfx anywhere
in str. A correct solution is to just do a string compare against the
correct length prefix of str:

let starts_width ~str ~prefix = if String.length str < String.length
prefix then false else String.sub str 0 (String.length prefix) = prefix

E.

@UnixJunkie
Copy link
Author

No, the matched substring must start at index 0 in the code I gave.
That's correct and I tried it extensively in a toplevel.
I'll send a pull request.

The documentation of the Str module is not that crystal clear.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants