2

I want to split a string using spaces but not considering double quotes or single quotes.

I tried using Regex for splitting a string using space when not surrounded by single or double quotes but it failed in some cases.

Input : It is a "beautiful day"'but i' cannot "see it"

and the output should be

It
is
a
"beautiful day"'but i'
cannot
"see it"

The regex in above link resulted in

It
is
a
"beautiful day"
'but i'
cannot
"see it"

I want "beautiful day"'but i' in the one line.

Can somebody help me in writing the correct regex?

Community
  • 1
  • 1
Krishna M
  • 1,135
  • 2
  • 16
  • 32

1 Answers1

5

This regex passes your test:

" (?=(([^'\"]*['\"]){2})*[^'\"]*$)"

It's splitting on a space, but only when the space is not inside quotes, which it tests by using a look ahead to assert that there is an even number of quotes following the space.

There are some edge cases this won't work for, but if your input is "well formed" (ie quotes are balanced) this will work for you. If quotes are not balanced, it is still doable - you would need to use two look aheads - one for each quote type.


Here's some test code:

String s = "It is a \"beautiful day\"'but i' cannot \"see it\"";
String[] parts = s.split(" (?=(([^'\"]*['\"]){2})*[^'\"]*$)");
for (String part : parts)
    System.out.println(part);

Output:

It
is
a
"beautiful day"'but i'
cannot
"see it"
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • When i modify the string to **It is a \"beautiful day'but i' \"cannot \"see it\"** It fails.Can u please explain how it works ? – Krishna M Feb 07 '14 at 12:56
  • 1
    Please tell me what "success" would look like for this new string. – Bohemian Feb 07 '14 at 13:07
  • The desired output is just like **"beautiful day'but i'"**. But i got **""beautiful day"'but i'"** and **"i' "cannot"** in consecutive lines – Krishna M Feb 07 '14 at 13:09
  • what exactly are your rules for splitting? – Bohemian Feb 07 '14 at 13:15
  • I couldn't understand you clearly. But as for i understood, i used the same regex rule given by you for splitting. I want split a string with spaces and that spaces should not between a double quote or single quote. I hope i was answered your question. If you want any clarifications, i am ready to give. Please help me to get through this – Krishna M Feb 07 '14 at 13:21