Split up a list at each element satisfying a predicate (Scala)

后端 未结 2 1730
谎友^
谎友^ 2020-12-10 13:36

In a text file I have data in the form:

1)
text
text
2)
more text
3)
even more text
more even text
even more text
...

I read it as a list o

2条回答
  •  感情败类
    2020-12-10 14:04

    I have the honor, to add an answer next to the great @MartinOdersky!

    From Scala 2.13 we can use the List.unfold:

    List.unfold(input) {
      case Nil =>
        None
      case x :: as =>
        as.span(!_.matches("""\d+\)""")) match {
          case (prefix, Nil) =>
            Some(x :: prefix, List.empty)
          case (prefix, suffix) =>
            Some(x :: prefix, suffix)
        }
    }
    

    Code run at Scastie.

提交回复
热议问题