我有如下记录。
1,2018,Abc,2018-04-19,Abc,Abc,Abc,b,n,0,Abc,33,0,Abc,“Sql,Xyz”,Abc, ABC,
我想用“,”逗号分隔符拆分字符串,但我希望 Sql,Xyz 作为单个字符串而不是两个不同的字符串,如“Sql adn XYZ“即可。 那么有人可以帮助我。提前谢谢。
答案 0 :(得分:1)
这可能适合你。
def mySplit(str: String): List[String] = {
var elems = List[String]()
// break down by quotes first
val quotes = str.split("\"")
for(i <- 0 to quotes.length - 1) {
if(i % 2 == 0) {
// break down by commas second
val subelems = quotes(i).split(",")
for(j <- 0 to subelems.length - 1) {
if(!subelems(j).isEmpty)
elems = elems :+ subelems(j)
// ignore empty elements
}
} else {
// save "whole strings" and
// don't break into commas
elems = elems :+ quotes(i)
}
}
return elems
}
像这样使用它:
// quick test
val str = "1,2018,Abc,2018-04-19,Abc,Abc,Abc,b,n,0,Abc,33,0,Abc,\"Sql, Xyz\",Abc,Abc"
val list = mySplit(str)
答案 1 :(得分:0)
我已经完成了,使用下面的正则表达式
val str= "1,2018,Abc,2018-04-19,Abc,Abc,Abc,b,n,0,Abc,33,0,Abc,\"Sql, Xyz\",Abc,Abc"
val list=str.split(",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)")
list.foreach( x => println(x))