Scoop API

scoop:scoop.regex:0.1.0

src/split.scoop

Selected production source · src/split.scoop

1package scoop.regex
3import scoop.sequences.*
5/**
6 * Splits on matches, retaining empty segments and omitting delimiter captures. Zero limit means
7 * unlimited; a positive limit leaves the remaining text in the final segment. Negative limits throw.
8 */
9public fun Regex.split(input: String, limit: Long = 0L): List<String> = splitToSequence(input, limit).toList()
11/** Produces the same segments as split lazily. Each iterator has independent progress. */
12public fun Regex.splitToSequence(input: String, limit: Long = 0L): Sequence<String> {
13 checkedHandle()
14 if (limit < 0L) throw IllegalArgumentException(Some("split limit must be nonnegative"))
15 return RegexSplits(this, input, limit)
18private class RegexSplits(private val regex: Regex, private val input: String, private val limit: Long) : Sequence<String> {
19 public override operator fun iterator(): Iterator<String> = RegexSplitIterator(regex, input, limit)
22private class RegexSplitIterator(regex: Regex, private val input: String, private val limit: Long) : Iterator<String> {
23 private val matches: Iterator<MatchResult> = RegexIterator(regex, input, 0L)
24 private var position: Long = 0L
25 private var emitted: Long = 0L
26 private var finished: Boolean = false
28 public override fun next(): String? {
29 if (finished) return None
30 if (input.byteLength == 0L || (limit > 0L && emitted == limit - 1L)) return tail()
31 when (val match = matches.next()) {
32 case None -> return tail()
33 case Some(val value) -> {
34 val result = regexSlice(input, position, value.byteStart)
35 position = value.byteEnd
36 emitted += 1L
37 return Some(result)
38 }
39 }
40 }
42 private fun tail(): String? {
43 val result = regexSlice(input, position, input.byteLength)
44 finished = true
45 return Some(result)
46 }