问题
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
}
回答1:
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
回答2:
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:
- Replace any run of spaces \s* with a single space
- Split the string into pieces based on the single space
来源:https://stackoverflow.com/questions/43723523/how-to-get-string-from-several-double-quotes-in-a-line