Home > Net >  split string between 2 char based index
split string between 2 char based index

Time:11-16

How can we split a text between two char in Kotlin?

Example string:

base_id:94, user_id: 320903, is_Active=1

I want to get only user_id so "320903". But I couldn't do that.

CodePudding user response:

One way to get it is using regex and you can customize it to cover base_id and is_Active

val pattern = Pattern.compile("user_id: (?<id>[0-9] )")
val matcher = pattern.matcher(text)
if (matcher.find()) {
    val group = matcher.group("id").trim()
    println(group)
}

The output will be : 320903

Or you can do that with split only and you will get the same result

val items = text.split(",")
val userId = items[1].split(":")[1].trim()
println(userId)

That will work correctly with your example but make sure but for other cases, you may need to customize it or give us many examples to cover them

You can handle the 3 values with one function that support optional whitespace and : or =

fun getValueByTagName(text : String, tag : String) : String {
    val pattern = Pattern.compile("$tag[:=][ ]*(?<id>[0-9] )")
    val matcher = pattern.matcher(text)
    return if (matcher.find())
        matcher.group("id").trim()
    else ""
}

To use it

println(getValueByTagName(text, "base_id"))      // 94
println(getValueByTagName(text, "user_id"))      // 320903
println(getValueByTagName(text, "is_Active"))    // 1

CodePudding user response:

Another solution:

Method 1: If your string has exactly the same format that you have shown in the example.

val indexOfUserId = s.indexOf("user_id") // find index of the substring "user_id"
val end = s.indexOf(',', indexOfUserId) // find index of ',' after user_id
val userId s.substring(indexOfUserId   9, end) // take the substring assuming that userId starts exactly 9 characters after the "u" in "user_id"

Method 2: If your format can vary (in spaces and symbols). Also assuming that user_id is always a number.

val indexOfUserId = s.indexOf("user_id")
val start = s.findAnyOf(List(10) { "$it" }, indexOfUserId)!!.first // find the first digit after "user_id"
val userId = s.substring(start).takeWhile { it.isDigit() } // start from the first digit and continue as long as you are getting digits

Here, List(10) { "$it" } is just a list of all digits in string format and findAnyOf:

Finds the first occurrence of any of the specified [strings] in this char sequence, starting from the specified [startIndex]

Try it yourself

  • Related