Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

Split string on spaces in Java, except if between quotes (i.e. treat "hello world" as one token)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's how:

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);

Output:

[Location, "Welcome  to india", Bangalore, Channai, "IT city", Mysore]

The regular expression simply says

  • [^"]     - token starting with something other than "
  • S*       - followed by zero or more non-space characters
  • ...or...
  • ".+?"   - a "-symbol followed by whatever, until another ".

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...