Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin split with regex work not as expected

I am trying to split string with chunks of 16 chars length. So first of all I create string with 64 length

val data = "Some string"
data = String.format("%-64s", data)

Then I split it with regex

 val nameArray = data.split(Regex("(?<=\\G.{16})").toPattern())

Here I expext to get 4 chunks with 16 chars, but I got only 2, where first is 16 and second is 48.

Where am I wrong here?

Kotlin 1.2.61, Oracle JDK 1.8.0_181-b13, Windows 10

enter image description here

like image 952
Anton A. Avatar asked Nov 08 '22 02:11

Anton A.


1 Answers

data.chunked(16)

should be sufficient to solve the problem as you described it. It should be available in the version you use, since its documented as such here.

I have tried your approach and the one from Keng, but with very different results as described here.

https://pl.kotl.in/HJpQSfdqi

import java.net.URI
import java.util.*
import java.time.LocalDateTime
import java.time.temporal.*


/**
 * You can edit, run, and share this code. 
 * play.kotlinlang.org 
 */

fun main() {    
    var data = "Some string"
    data = String.format("%-64s", data)

    println(data.length)    
    // 1st approach
    var nameArray = data.split(Regex("(?<=\\G.{16})").toPattern())

    println(nameArray)
    nameArray.forEach{ it -> println(it.length) }
    println()

    // 2nd approach
    nameArray = data.split(Regex(".{16}").toPattern())

    println(nameArray)
    nameArray.forEach{ it -> println(it.length) }
    println()


    data.chunked(16).forEach{ it -> println(it.length) }
}

When I run that code, the proposed regex-methods return arrays of length 5, which is caused by an empty element at the end. I don't quite understand why, but I hope this helps to solve your problem.

like image 51
Benjamin Basmaci Avatar answered Nov 14 '22 21:11

Benjamin Basmaci