[英]Elegant algorithm to split a string by comma or double quotes pair in Java
[英]Split a String with delimiter - , (comma) and double quotes over every value in java
我有一個字符串值 - ["My, Fantasy, text", "My, other, value"]
我想將輸出作為帶有元素的列表 -
My, fancy, text
My, other, value
封閉括號將被刪除。封閉括號“[”和“]”可能不存在。 '
假設要求是刪除所有方括號並將雙引號之間的文本作為單個字符串查找。 下面的代碼可能會有所幫助
String[] data = Stream.of(
input.replaceAll("\\[", "")//replace all [
.replaceAll("\\]","")//replace all ]
.replaceAll("\",","")// replace the comma between strings,
.split("\""))//now split the string based on double quotes
.filter(str ->str.trim().length() > 1)//filtering out the string which contains only whitespace
.toArray(String[]::new);//collecting the data in an array
//data[0] = My, fancy, text
//data[1] = My, other, value
My own solution is not very elegant thats the problem
public static void main(String []args){
String s = "[\"I,my,me\", \"We,our,us\"]";
if(s.startsWith("[") && s.endsWith("]")) {
s = s.substring(1, s.length() -1);
}
System.out.println(s);
for (String a : s.split("\"")) {
if(!a.isEmpty() && !a.equals(","))
System.out.println(a);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.