基本上,我需要a b c
(单独)
从一条线(每个之间有任意数量的空格)
"a" "b" "c"
Run Code Online (Sandbox Code Playgroud)
是否可以使用string.split执行此操作?
我从什么都试过split(".*?\".*?")
来("\\s*\"\\s*")
.
后者工作,但它将数据拆分为数组的每个其他索引(1,3,5),其他索引为空""
编辑:
我希望这适用于任何数量/变化的字符,而不仅仅是a,b和c.(例如:"apple" "pie" "dog boy"
)
为我的特定问题找到了解决方案(可能效率最低):
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
}
Run Code Online (Sandbox Code Playgroud)
您可以使用模式:
String str = "\"a\" \"b\" \"c\" \"\"";
Pattern pat = Pattern.compile("\"[a-z]+\"");
Matcher mat = pat.matcher(str);
while (mat.find()) {
System.out.println(mat.group());
}
Run Code Online (Sandbox Code Playgroud)
对于像这样的输入,"a" "b" "c" ""
那么:
产量
"a"
"b"
"c"
Run Code Online (Sandbox Code Playgroud)
如果你想获得没有引号的abc,你可以使用:
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));
}
Run Code Online (Sandbox Code Playgroud)
产量
a
b
c
Run Code Online (Sandbox Code Playgroud)
如果您可以使用引号之间的空格 \"([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));
}
Run Code Online (Sandbox Code Playgroud)
产量
a
b
c include spaces
Run Code Online (Sandbox Code Playgroud)