Kotlin 正規表現で文字列(string)の最後の文字を置換する

環境
Windows11 pro 64bit
java 19.0.1
kotlin 1.7.20-release-201

構文
//text=対象の文字列, replace=置換後の文字
val result = text.replace(“.$".toRegex(), replace)
replace()は、対象の文字列(string)の末尾の文字を置換した文字列を返します。
replace()の第1引数に「".$".toRegex()」、第2引数に置換後の文字を指定します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fun main() {
val text = "STUDY"
val result = text.replace(".$".toRegex(), "#")
println(result)
}
fun main() { val text = "STUDY" val result = text.replace(".$".toRegex(), "#") println(result) }
fun main() {
       val text = "STUDY"
    
       val result = text.replace(".$".toRegex(), "#")
    
    println(result)
}

実行結果
STUD#

Kotlin

Posted by arkgame