简体   繁体   中英

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

Basically, I need to get abc (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
}

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 abc 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 \\"([az\\\\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

You need to do a replacement first before you split the string, eg "a" "b" "c" to "a" "b" "c". String myLetters[] = myString.replaceAll("\\\\s*"," ").split(" ") should work through two steps:

  1. Replace any run of spaces \\s* with a single space
  2. Split the string into pieces based on the single space

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM