beginner beginner - 1 month ago 7
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
word
,
to
,
split
.

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

Answer

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: " + matcher.group(0));
        }
    }
}

demo

Comments