mahan
mahan

Reputation: 15035

Kotlin - add a single space between string and number

I have the following texts. I need to add a single space between the string and numbers.

Text1 -> Text 1

Text10 -> Text 10

Kotlin2 -> Kotlin 2

I used the following code, but it does not work.

fun addSpace(text: String): String {
   return text.split("\\D".toRegex()).joinToString(separator = " ") { it  }
}

It return only the number.

Upvotes: 1

Views: 1146

Answers (2)

AmrDeveloper
AmrDeveloper

Reputation: 4722

You can use regex groups and replaceAll

fun main() {
    val input = "Text1 Text10 Kotlin2"
    val pattern = Pattern.compile("([a-zA-Z]+)([0-9]+)")
    val matcher = pattern.matcher(input).replaceAll("$1 $2")
    println(matcher)
}

Output will be

Text 1 Text 10 Kotlin 2

Upvotes: 0

k314159
k314159

Reputation: 11307

You can just replace any occurrence of a string of digits with a space followed by those digits:

fun addSpace(text: String) = text.replace(Regex("\\d+" ), " \$0")

(The $ is escaped so that the Kotlin compiler doesn't treat it as interpolation.)

Upvotes: 4

Related Questions