Reputation: 3201
Suppose I have a string
123 --o 45 xyz 67 "abc def" " ghi jkl m" " " "" xy z
which I need to parse into an array of strings
["123", "--o", "45", "xyz", "67", "abc def", " ghi jkl m", " ", "", "xy", "z"]
My straight approach to split a string by spaces (split("\\s+")
) isn't suitable because it separates a string by spaces and doesn't consider double quotes.
But I also need to separate elements which is quoted (" ghi jkl m"
, "abc def"
, and " "
).
How can I modify my regular expression in method split
to achieve my goal?
UPD
We also should consider the spaces.
=> [a, "s ", abc, "", "ad"sdsd"sdsd"
]
"ad"sdsd"sdsd"
is a sinle element.
Upvotes: 2
Views: 132
Reputation: 174874
Split your input according to the below regex which uses a positive lookahead assertion.
String text = "123 --o 45 xyz 67 \"abc def\" \" ghi jkl m\" \" \" \"\" xy z";
String parts[] = text.split("\\s+(?=(?:\"[^\"]*\"|[^\"])*$)");
System.out.println(Arrays.toString(parts));
Output:
[123, --o, 45, xyz, 67, "abc def", " ghi jkl m", " ", "", xy, z]
Upvotes: 1