arrays - 将标题与String中的正文分开,或如何通过2 “\n”进行解析? Kotlin

标签 arrays regex kotlin

我有一个文本,应该保存在android string.xml资源中。为此,我想将其保存在Data类的列表中。

Title1

Body1 .....

Title2

Body2......



标题周围有2个换行符,我需要从正文中拆分标题。这该怎么做?是否有任何正则表达式模式?

更新:

如果正文包含多于1个段落:

Title1

Body1 .....

BodyContinuation

New Paragraph

Title2

Body2......



如何处理这种情况?

最佳答案

您可以使用kotlin本身来解析它,它将通过使用行序列以类似于regex的O(n)步骤进行解析。

例:

fun parseTitle(str: String): Sequence<String> = sequence {
    var emptyLines = 2
    str.lineSequence().forEach {
        when {
            emptyLines > 1 -> {
                yield(it)
                emptyLines = 0
            }
            it.isNotEmpty() -> emptyLines = 0
            else -> emptyLines++
        }
    }
}

val test =
    """
    Title1

    Body1 .....


    Title2

    Body2......
    """.trimIndent()

println(parseTitle(test).toList()) // [Title1, Title2]

编辑:

如果有多个段落包含任意数量的换行符,则过滤掉它们的唯一约束就是大小。

/**
 * [str] is the input string, [maxLen] is maximum length until which line
 * should be expected to be a title
 */
fun parseTitle(str: String, maxLen: Int): Sequence<String> =
    str.lineSequence()
        .filter { it.isNotEmpty() }
        .mapNotNull { if(it.length <= maxLen) it else null }
        // .toList()  // to trigger terminal operation and collect the result into list

关于arrays - 将标题与String中的正文分开,或如何通过2 “\n”进行解析? Kotlin ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62227600/

相关文章:

正则表达式 : how to match multiline and closetag

Python 正则表达式 : Finding input not matching a specific (variable-defined) length

android - Kotlin - 创建 Fragment newInstance 模式的惯用方式

android - Kotlin - 无法访问另一个类中的方法

c - 如何动态分配包含多个数组的结构体?

php - 在 while 循环中附加到数组是否安全?

c++ - 来自现有 std::array 的 std::initializer 列表,无需枚举每个元素

java - 在Android中通过httpost发送字节数组

java - 正则表达式检查字符串第一个字符是否是数字

java - IncompatibleClassChangeError : Class 'java.lang.VirtualMachineError' does not implement interface 'java.lang.CharSequence'