Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split string by space but escape spaces inside quotes (in java)? [duplicate]

I have a string like this:

"Video or movie"    "parent"    "Media or entertainment"    "1" "1" "1" "0" "0"

I would like to split it by the spaces but the space inside the quote should be ignored. So the splitted strings should be:

"Video or movie"
"parent"
"Media or entertainment"
"1"
...

The language is java.

like image 328
user3111525 Avatar asked Jan 20 '12 17:01

user3111525


People also ask

How do you split a string with double quotes?

Use method String. split() It returns an array of String, splitted by the character you specified.

How do you escape a double quote in Java?

The first method to print the double quotes with the string uses an escape sequence, which is a backslash ( \ ) with a character. It is sometimes also called an escape character.

What does split \\ s+ do in Java?

split("\\s+") will split the string into string of array with separator as space or multiple spaces. \s+ is a regular expression for one or more spaces.


1 Answers

this should do the job for you:

   final String s = "\"Video or movie\"    \"parent\"    \"Media or entertainment\"    \"1\" \"1\" \"1\" \"0\" \"0\"";
        final String[] t = s.split("(?<=\") *(?=\")");
        for (final String x : t) {
            System.out.println(x);
        }

output:

"Video or movie"
"parent"
"Media or entertainment"
"1"
"1"
"1"
"0"
"0"
like image 85
Kent Avatar answered Sep 29 '22 00:09

Kent