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
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
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.