为了账号安全,请及时绑定邮箱和手机立即绑定

Java/Kotlin:标记字符串忽略嵌套引号的内容

Java/Kotlin:标记字符串忽略嵌套引号的内容

慕桂英546537 2022-06-04 17:43:34
我想用空格分割一个字符,但将空格保留在引号内(以及引号本身)。问题是,引号可以嵌套,而且我需要对单引号和双引号都这样做。所以,从this "'"is a possible option"'" and ""so is this"" and '''this one too''' and even ""mismatched quotes"我想得到的行[this, "'"is a possible option"'", and, ""so is this"", and, '''this one too''', and, even, ""mismatched quotes"]。这个问题已经被问过了,但不是我要问的确切问题。这里有几个解决方案:一个使用匹配器(在这种情况下"""x"""将被拆分为[""", x"""],所以这不是我需要的)和 Apache Commons (它可以使用"""x"""但不能使用""x"",因为它需要前两个双引号并留下最后两个与x)。也有人建议手动编写一个函数,但这是最后的手段。
查看完整描述

1 回答

?
森林海

TA贡献2011条经验 获得超2个赞

您可以使用以下正则表达式来实现:["']+[^"']+?["']+. 使用该模式,您可以检索要拆分的索引,如下所示:


val indices = Regex(pattern).findAll(this).map{ listOf(it.range.start, it.range.endInclusive) }.flatten().toMutableList()

剩下的就是用子字符串构建列表。这里完整的功能:


fun String.splitByPattern(pattern: String): List<String> {


    val indices = Regex(pattern).findAll(this).map{ listOf(it.range.start, it.range.endInclusive) }.flatten().toMutableList()


    var lastIndex = 0

    return indices.mapIndexed { i, ele ->


        val end = if(i % 2 == 0) ele else ele + 1 // magic


        substring(lastIndex, end).apply {

            lastIndex = end

        }

    }

}

用法:


val str = """

this "'"is a possible option"'" and ""so is this"" and '''this one too''' and even ""mismatched quotes"

""".trim()


println(str.splitByPattern("""["']+[^"']+?["']+"""))

输出:


[this , "'" is a possible option"'", and , ""so is this"", and , '''this one too''', and even , ""mismatched quotes"]


在Kotlin 的操场上试试吧!


查看完整回答
反对 回复 2022-06-04
  • 1 回答
  • 0 关注
  • 238 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号