beginner beginner - 9 months ago 48
Java Question

Java split by white spaces with condition

I want to split string by white spaces. However if words are enclosed with quotation marks, then treat them as a single word.

For example

Word to split
. I will get

but if
"word to" split
i should get
"word to"
. quotation mark remains.

Answer Source

Is that what you want??

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TmpTest {
    public static void main(String args[]) {
        final String regex = "\".*?\"|\\b\\w+\\b";
        final String string = "\"word to\" split i should get \"word to2\", split.";

        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " +;