How to get a string from multiple double quotes in a string?

Basically, I need to get a b c(separately)

from a line (with any number of spaces between each "

"a" "b" "c"

Can this be done using string.split?

I tried everything: from split(".*?\".*?")to ("\\s*\"\\s*").

The latter works, but it splits the data into each other index of the array (1, 3, 5), and the rest are empty ""

Edit:

I would like this to apply with any number / variation of characters, not just a, b and c. (example: "apple" "pie" "dog boy")

Found a solution for my specific problem (maybe not the 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
}
+6
source share
2 answers

You can use a template 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());
}

"a" "b" "c" "", :

"a"
"b"
"c"

b c , :

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));
}

a
b
c

, \"([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));
}

a
b
c include spaces

+6

, , "a"   "b" "c" "a" "b" "c". String myLetters[] = myString.replaceAll("\\s*"," ").split(" ") :

+2

Source: https://habr.com/ru/post/1016913/


All Articles