Kotlin与正则表达式工作不合预期 [英] Kotlin split with regex work not as expected

查看:82
本文介绍了Kotlin与正则表达式工作不合预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用16个字符长度的块拆分字符串. 所以首先我创建长度为64的字符串

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())

在这里我得到了4个带有16个字符的块,但我只有2个,其中第一个是16,第二个是48.

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

我在哪里错了?

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

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

推荐答案

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.

我尝试了您的方法,以及 Keng 中的方法,但此处描述的结果截然不同.

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) }
}

当我运行该代码时,建议的正则表达式方法返回长度为5的数组,这是由结尾处的空元素引起的.我不太清楚为什么,但是我希望这有助于解决您的问题.

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.

这篇关于Kotlin与正则表达式工作不合预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆