どうも、ちょげ(@chogetarou)です。
文字列(string)を正規表現で置換する方法を紹介します。
方法

文字列(string)を正規表現で置換するには、replace()を使います。
まず、文字列からreplace()を呼び出します。
そして、replace()の第1引数に正規表現のパターン、第2引数に置換後の文字列を指定します。
//text=対象の文字列, pattern=正規表現のパターン, replace=置換後の文字列
val result = text.replace("pattern".toRegex(), replace)
上記のreplace()は、呼び出した文字列(string)の正規表現にマッチした文字を全て置換します。
使用例
fun main() {
val text = "ABC1DEF3GHI5J99K"
val result = text.replace("[1-9]".toRegex(), "?")
println(result)
}
出力:
ABC?DEF?GHI?J??K
コメント