如何基于空格拆分String
,但将引用的子串作为一个单词?
示例:
Location "Welcome to india" Bangalore Channai "IT city" Mysore
应将其存储在ArrayList
Location
Welcome to india
Bangalore
Channai
IT city
Mysore
答案 0 :(得分:124)
以下是:
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*
- 后跟零个或多个非空格字符".+?"
- 一个"
- 符号后跟任何内容,直到另一个"
。