如何String根据空间拆分a ,但将带引号的子字符串当作一个词?
String
例:
Location "Welcome to india" Bangalore Channai "IT city" Mysore
它应该存储ArrayList为
Location Welcome to india Bangalore Channai IT city Mysore
就是这样:
String str = "Location \"Welcome to india\" Bangalore " + "Channai \"IT city\" Mysore"; List<String> list = new ArrayList<String>(); Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(str); while (m.find()) list.add(m.group(1)); // Add .replace("\"", "") to remove surrounding quotes. System.out.println(list);
输出:
[Location, "Welcome to india", Bangalore, Channai, "IT city", Mysore]
正则表达式简单地说
[^"]
"
\S*
...or...
".+?"