Kotlin String.split,当分隔符在引号内时忽略 [英] Kotlin String.split, ignore when delimiter is inside a quote
本文介绍了Kotlin String.split,当分隔符在引号内时忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串:
Hi there, "Bananas are, by nature, evil.", Hey there.
我想用逗号分隔字符串作为定界符.如何获取.split方法以忽略引号内的逗号,以便它返回3个字符串而不是5个字符串.
I want to split the string with commas as the delimiter. How do I get the .split method to ignore the comma inside the quotes, so that it returns 3 strings and not 5.
推荐答案
您可以在拆分方法中使用regex
You can use regex
in split method
根据此答案,以下正则表达式仅与,
标记之外的,
匹配
According to this answer the following regex only matches ,
outside of the "
mark
,(?=(?:[^ \] \" [^ \] \") [^ \] $)
因此,请尝试以下代码:
so try this code:
str.split(",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*\$)".toRegex())
这篇关于Kotlin String.split,当分隔符在引号内时忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文