scoop:scoop.regex:0.1.0
src/split.scoop
Selected production source · src/split.scoop
1
package scoop.regex3
import scoop.sequences.*5
/**6
* Splits on matches, retaining empty segments and omitting delimiter captures. Zero limit means7
* unlimited; a positive limit leaves the remaining text in the final segment. Negative limits throw.8
*/9
public 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. */12
public 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)16
}18
private 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)20
}22
private 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 = 0L25
private var emitted: Long = 0L26
private var finished: Boolean = false28
public override fun next(): String? {29
if (finished) return None30
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.byteEnd36
emitted += 1L37
return Some(result)38
}39
}40
}42
private fun tail(): String? {43
val result = regexSlice(input, position, input.byteLength)44
finished = true45
return Some(result)46
}47
}