OCaml是否像Python一样有String.split函数?

lll*_*lll 7 ocaml split string-parsing

我用它来分割字符串:

 let split = Str.split (Str.regexp_string " ") in
   let tokens = split instr in
 ....
Run Code Online (Sandbox Code Playgroud)

但问题是,例如这里是我要解析的句子:

pop     esi
Run Code Online (Sandbox Code Playgroud)

并且在拆分之后它变成了(我使用辅助函数来打印tokens列表中的每个项目):

item: popitem: item: item: item: esi
Run Code Online (Sandbox Code Playgroud)

请注意,令牌列表中有三个空格.

我想知道string.splitPython中是否有类似可以解析的instr方式:

item: popitem: esi
Run Code Online (Sandbox Code Playgroud)

可能吗?

Jef*_*eld 14

不要使用Str.regexp_string,它仅用于匹配固定字符串.

使用 Str.split (Str.regexp " +")


gle*_*nsl 9

从 OCaml 4.04.0 开始,还有String.split_on_char,您可以将其结合起来List.filter删除空字符串:

# "pop     esi"
  |> String.split_on_char ' '
  |> List.filter (fun s -> s <> "");;
- : string list = ["pop"; "esi"]
Run Code Online (Sandbox Code Playgroud)

不需要外部库。


Ant*_*ama 7

使用Jane Street的核心库,您可以:

let python_split x =
  String.split_on_chars ~on:[ ' ' ; '\t' ; '\n' ; '\r' ] x
  |> List.filter ~f:(fun x -> x <> "")
;;
Run Code Online (Sandbox Code Playgroud)