一尘不染

在Java中的空格上拆分字符串,除非双引号之间(即将\“ hello world \”视为一个标记)

java

如何String根据空间拆分a ,但将带引号的子字符串当作一个词?

例:

Location "Welcome  to india" Bangalore Channai "IT city"  Mysore

它应该存储ArrayList为

Location
Welcome to india
Bangalore
Channai
IT city
Mysore

阅读 893

收藏
2020-03-06

共1个答案

一尘不染

就是这样:

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...
  • ".+?" - “符号-后跟任何符号,直到另一个符号"
2020-03-06