【问题标题】:Does OCaml have String.split function like Python?OCaml 有像 Python 一样的 String.split 函数吗?
【发布时间】:2014-06-05 23:07:48
【问题描述】:

我正在使用它来拆分字符串:

 let split = Str.split (Str.regexp_string " ") in
   let tokens = split instr in
 ....

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

pop     esi

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

item: popitem: item: item: item: esi

看,令牌列表中有三个空格

我想知道是否有类似 Python 中的 string.split 可以这样解析 instr

item: popitem: esi

有可能吗?

【问题讨论】:

    标签: split ocaml string-parsing


    【解决方案1】:

    从 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"]
    

    不需要外部库。

    【讨论】:

      【解决方案2】:

      这就是我将台词分成单词的方式:

      open Core.Std
      let tokenize line = String.split line ~on: ' ' |> List.dedup
      

      注意空格字符周围的单引号。

      这是String.split 的文档:link

      【讨论】:

        【解决方案3】:

        使用Jane Street's Core library,您可以:

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

        【讨论】:

          【解决方案4】:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-05-19
            • 2018-03-31
            • 1970-01-01
            • 2012-02-09
            • 1970-01-01
            • 1970-01-01
            • 2012-07-24
            • 2011-12-02
            相关资源
            最近更新 更多