java - Regex to split a string using spaces but not considering double quotes or single quotes

两盒软妹~` 提交于 2019-12-04 15:36:48

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!