Created
February 16, 2024 15:01
-
-
Save gold24park/9b34b9f4753072456a5c609321b61cf2 to your computer and use it in GitHub Desktop.
Kotlin Text Replacer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main(args: Array<String>) { | |
val param = mapOf( | |
"PS" to mapOf( | |
"ts" to mapOf( | |
"pt" to "Lou", | |
"age" to 28 | |
) | |
), | |
"ENV" to mapOf( | |
"ver" to 1.0 | |
) | |
) | |
val str = "My Name is :{PS.ts.pt}, - :{ENV.ver} version" | |
val (ret, d) = _replaceString(str, param) | |
println(ret) // "My Name is Lou, - 1.0 version" | |
} | |
fun find(name: String, param: Map<String, Any>): String? { | |
name.split(".").fold(param) { p, s -> | |
when (val r = p[s]) { | |
is Map<*, *> -> r as Map<String, Any> | |
null -> p | |
else -> return r.toString() | |
} | |
} | |
return null | |
} | |
fun _replaceString(source: String, param: Map<String, Any>): Pair<String, Boolean> { | |
var dirty = false | |
val result = source.replace(":\\{([^}]+)}".toRegex()) { matchResult -> | |
val (str, n) = matchResult.groups.mapNotNull { it?.value }.take(2) | |
val r = find(n, param) | |
dirty = r != null | |
r.takeIf { dirty } ?: str | |
} | |
return result to dirty | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment