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?

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

5 Comments

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 ?
Please tell me what "success" would look like for this new string.
The desired output is just like "beautiful day'but i'". But i got ""beautiful day"'but i'" and "i' "cannot" in consecutive lines
what exactly are your rules for splitting?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.