简体   繁体   中英

Split comma-separated string but ignore comma followed by a space

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]);

}

output: [Today, and tomorrow, 2, 1, 2, 5, 0]

Today

(space) and tomorrow

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)

Use a negative look ahead:

String[] titleSep = title.split(",(?! )");

The regex (?! ) means "the input following the current position is not a space".

FYI a negative look ahead has the form (?!<some regex>) and a positive look ahead has the form (?=<some regex>)

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]);

The output is:

[Today, and tomorrow, 2, 1, 2, 5, 0]
Today, and tomorrow
2 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM