分割逗号分隔的字符串,但忽略逗号后跟空格
问题描述:
public static void main(String [] args){
public static 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]
output: [Today, and tomorrow, 2, 1, 2, 5, 0]
今天
(空格)和明天
我想将今天和明天"视为代表titleSep的第一个索引值的短语(不想以逗号分隔).什么是split方法参数,它将仅以逗号分隔字符串而不用空格分隔?(Java 8)
I want to treat "Today, and tomorrow" as a phrase representing the first index value of titleSep (do not want to separate at comma it contains). What is the split method argument that would split the string only at commas NOT followed by a space? (Java 8)
答
split函数的参数是一个正则表达式,因此我们可以使用负前瞻来按逗号分隔,而不用空格分隔:
The argument to the split function is a regex, so we can use a negative lookahead to split by comma-not-followed-by-space:
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