[英]Split comma-separated string but ignore comma followed by a space
公共靜態void main(String [] args){
String title = "Today, and tomorrow,2,1,2,5,0";
String[] titleSep = title.split(",");
System.out.println(Arrays.toString(titleSep));
System.out.println(titleSep[0]);
System.out.println(titleSep[1]);
}
輸出:[今天和明天,2、1、2、5、0]
今天
(空間)和明天
我想將“今天和明天”視為代表titleSep的第一個索引值的短語(不想在包含的逗號處分開)。 什么是split方法參數,它將僅以逗號分隔字符串而不用空格分隔? (Java 8)
負面評價:
String[] titleSep = title.split(",(?! )");
正則表達式(?! )
意思是“當前位置后面的輸入不是空格”。
僅供參考,負面展望的形式為(?!<some regex>)
,正面展望的形式為(?=<some regex>)
split函數的參數是一個正則表達式,因此我們可以使用負前行來按逗號分隔,而不是按空格分隔:
String title = "Today, and tomorrow,2,1,2,5,0";
String[] titleSep = title.split(",(?! )"); // comma not followed by space
System.out.println(Arrays.toString(titleSep));
System.out.println(titleSep[0]);
System.out.println(titleSep[1]);
輸出為:
[Today, and tomorrow, 2, 1, 2, 5, 0]
Today, and tomorrow
2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.