Scoop API

scoop:scoop.regex:0.1.0

src/callbacks.scoop

Selected production source · src/callbacks.scoop

1package scoop.regex
3/**
4 * Replaces every match with a callback result. Callbacks run after the native match and borrow
5 * have ended; exceptions propagate without returning partial output.
6 */
7public fun Regex.replace(input: String, transform: (MatchResult) -> String): String =
8 callbackReplacement(this, input, false, transform)
10/** Replaces the first match with a callback result, after ending the native input borrow. */
11public fun Regex.replaceFirst(input: String, transform: (MatchResult) -> String): String =
12 callbackReplacement(this, input, true, transform)
14private fun callbackReplacement(regex: Regex, input: String, first: Boolean, transform: (MatchResult) -> String): String {
15 val output = StringBuilder()
16 var position = 0L
17 var replaced = false
18 for (match in regex.findAll(input)) {
19 output.append(regexSlice(input, position, match.byteStart))
20 output.append(transform(match))
21 position = match.byteEnd
22 replaced = true
23 if (first) break
24 }
25 if (!replaced) return input
26 output.append(regexSlice(input, position, input.byteLength))
27 return output.toString()
30internal fun regexSlice(input: String, start: Long, end: Long): String {
31 @Unsafe {
32 return input.withUtf8Bytes { bytes, _ ->
33 @Unsafe { return@withUtf8Bytes String.fromUtf8(bytes + start, end - start) }
34 }
35 }