Sneh
Sneh

Reputation: 53

Split a string on spaces but not if space is inside quotes(quoted part can be like xxx"x x x"xxx

Input

abc hello" I am batman"xoxo bat man

Output

I am using \"(.*?)\" to grab the stuff inside quotes but can't grab the remaining non-whitespace part.

Upvotes: 2

Views: 71

Answers (2)

iviorel
iviorel

Reputation: 312

You could split the string using the ". Like

String s= "abc hello\" I am batman\"xoxo bat man";
String[] splittedString = s.split("\"");

splittedString will be "abc hello", " I am batman", "xoxo bat man". And use only the odd index from splittedString.

List<String> result = new ArrayList<String>();
for(int i = 0; i < splittedString.lengt; i++){
  if (i % 2 == 0) {
    result.addAll(Arrays.asList(splittedString[i].split(" ")));
  } else {
    result.add(splittedString[i]);
  }
}

Upvotes: 0

azro
azro

Reputation: 54148

You can do it by using a mathing pattern, and then remove the " :

  • pattern (?:"[^"]*"|\S)+ : non-capturing group that will
    • if find a " will wait (take all non-quote char [^"]) the second " to look for space
    • if find a letter, take all non-space char (\S)
  • replace " but empty string

String str = "abc hello\" I am batman\"xoxo bat man";
Matcher m = Pattern.compile("(?:\"[^\"]*\"|\\S)+").matcher(str);
List<String> res = new ArrayList<>();
while (m.find())
    res.add(m.group().replaceAll("\"", ""));

System.out.println(res);       //[abc, hello I am batmanxoxo, bat, man]

Upvotes: 2

Related Questions