Reputation: 11
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)
Upvotes: 1
Views: 1134
Reputation: 10992
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
Upvotes: 3
Reputation: 424983
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>)
Upvotes: 3