replace First
Требования к платформе и версии: Common (1.0)
inline fun CharSequence.replaceFirst(regex: Regex, replacement: String): String
Заменяет первое вхождение заданного регулярного выражения regex в этой последовательности символов указанным выражением replacement.
Это вспомогательная функция, эквивалентная regex.replaceFirst(this, replacement). Подробную информацию о её поведении и синтаксисе подстановки выражения replacement см. в Regex.replaceFirst.
Примеры
import kotlin.test.*
fun main() {
//sampleStart
val text = "The events are on 15-09-2024 and 16-10-2024."
// Regex to match dates in dd-mm-yyyy format
val dateRegex = "(?<day>\\d{2})-(?<month>\\d{2})-(?<year>\\d{4})".toRegex()
// Replacement expression that puts day, month and year values in the ISO 8601 recommended yyyy-mm-dd format
val replacement = "\${year}-\${month}-\${day}"
// Replacing the first occurrence of a date from dd-mm-yyyy to yyyy-mm-dd format
println(text.replaceFirst(dateRegex, replacement)) // The events are on 2024-09-15 and 16-10-2024.
// One can also reference the matched groups by index
println(text.replaceFirst(dateRegex, "$3-$2-$1")) // The events are on 2024-09-15 and 16-10-2024.
// Using a backslash to include the special character '$' as a literal in the result
println(text.replaceFirst(dateRegex, "$3-\\$2-$1")) // The events are on 2024-\$2-15 and 16-10-2024.
//sampleEnd
}
expect fun String.replaceFirst(oldChar: Char, newChar: Char, ignoreCase: Boolean = false): String
Возвращает новую строку, в которой первое вхождение oldChar заменено на newChar.
expect fun String.replaceFirst(oldValue: String, newValue: String, ignoreCase: Boolean = false): String
Возвращает новую строку, полученную заменой первого вхождения подстроки oldValue в этой строке указанной строкой newValue.
Требования к платформе и версии: JS (1.1), JVM (1.0), Native (1.3), Wasm-JS (1.8), Wasm-WASI (1.8)
actual fun String.replaceFirst(oldChar: Char, newChar: Char, ignoreCase: Boolean = false): String
Возвращает новую строку, в которой первое вхождение oldChar заменено на newChar.
actual fun String.replaceFirst(oldValue: String, newValue: String, ignoreCase: Boolean = false): String
Возвращает новую строку, полученную заменой первого вхождения подстроки oldValue в этой строке указанной строкой newValue.
© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/replace-first.html