How to get string from several double quotes in a line?

java, regex, string

Solution

You can use pattern instead :

String str = "\"a\" \"b\" \"c\" \"\"";
Pattern pat = Pattern.compile("\"[a-z]+\"");
Matcher mat = pat.matcher(str);

while (mat.find()) {
    System.out.println(mat.group());
}

For inputs like this `"a" "b" "c" ""` then the :

Output

"a"
"b"
"c"

If you want to get a b c without quotes you can use :

String str = "\"a\" \"b\" \"c\" \"\"";
Pattern pat = Pattern.compile("\"([a-z]+)\"");
Matcher mat = pat.matcher(str);

while (mat.find()) {
    System.out.println(mat.group(1));
}

Output

a
b
c

String with spaces

If you can have spaces between quotes you can use `\"([a-z\\s]+)\"`

String str = "\"a\" \"b\" \"c include spaces \" \"\"";
Pattern pat = Pattern.compile("\"([a-z\\s]+)\"");
Matcher mat = pat.matcher(str);

while (mat.find()) {
    System.out.println(mat.group(1));
}

Output

a
b
c include spaces

Ideone

Problem

Basically, I need to get `a b c` (separately) from a line (with any amount of spaces between each " ``` "a" "b" "c" ``` Is it possible to do this using string.split? I've tried everything from `split(".*?\".*?")` to `("\\s*\"\\s*")`. The latter works, but it splits the data into every other index of the array (1, 3, 5) with the other ones being empty "" Edit: I'd like for this to apply with any amount/variation of characters, not just a, b and c. (example: `"apple" "pie" "dog boy"`) Found a solution for my specific problem (might not be most efficient): ``` Scanner abc = new Scanner(System.in); for loop { input = abc.nextLine(); Scanner in= new Scanner(input).useDelimiter("\\s*\"\\s*"); assign to appropriate index in array using in.next(); in.next(); to avoid the spaces } ```

Original source