Split a string into spaces in Java, except between quotes (for example, treat \ "hello world \" as a single token)

How do I split a String based on a space, but take the subtitles under quotation marks as one word?

Example:

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

it should be saved in an ArrayList as

 Location Welcome to india Bangalore Channai IT city Mysore 
+56
java
Oct 18 '11 at 8:21
source share
2 answers

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 just says

  • [^"] is a token starting with something other than "
  • \S* - followed by zero or more non-spatial characters
  • ... or...
  • ".+?" - a " is a character followed by everything, to another. "
+123
Oct 18 '11 at 8:35
source share

First split for double quotes:

 String s = 'Location "Welcome to india" Bangalore Channai "IT city" Mysore'; String[] splitted = s.split('"'); 

then split with spaces each line in a broken array

 for(int i = 0; i< splitted.length; i++){ //split each splitted cell and store in your arraylist } 
-one
Oct 18 '11 at 8:29
source share



All Articles