繁体   English   中英

将带引号的Java字符串拆分为不带引号的args

[英]Split Java string with quotes into args with no quotes

我需要将我的字符串分成3个arg ,每个arg都是引号内的内容,并将它们存储在单独的变量中。

这就是我所拥有的。 下面的代码接受所有命令行参数,并将它们组合为一个大String

我需要转换的字符串示例:

“METRO Blue Line” “Target Field Station Platform 1” “south”

它应该变成:

var1 = METRO Blue Line
var2 = Target Field Station Platform 1
var3 = south

我已经对split("\\"")进行了很多尝试,但是无论出于什么原因,它甚至都没有为我删除引号。

// Construct a string to hold the whole args. 
// Implemented it this way because args is separated by spaces
String combine = "";
for(int i = 0; i < args.length; i++)
{
    combine = combine.concat(args[i]);
    combine = combine.concat(" ");
}
System.out.println(combine);

您正在使用弯曲的引号(也称为智能引号)标记,而不是在代码中进行说明

Pattern pattern = Pattern.compile("[“”]");
    String text = "“METRO Blue Line” “Target Field Station Platform 1” “south” ";
    String arr[] = text.split("\\”");
    for (int i = 0; i < arr.length; i++) {
        System.out.println(pattern.matcher(arr[i]).replaceAll("").trim());
    }

符号不同于符号" 。如果使用split("\\"")进行split("\\"") ,则显然可以搜索"但不能搜索其他引用符号

您可以使用Matcher及其find方法轻松提取它们。 或者使用正确的分隔符使用splitting方法: split("” “") 请注意,第一个和最后一个元素将带有单引号,只需将其删除即可。


String input = "“METRO Blue Line” “Target Field Station Platform 1” “south”";
String[] elements = input.split("” “");

// Remove first quote
elements[0] = elements[0].substring(1);
// Remove last quote
String lastElement = elements[elements.length - 1];
elements[elements.length - 1] = lastElement.substring(0, lastElement.length() - 1);

// Output all results
for (String element : elements) {
    System.out.println(element);
}

输出为:

METRO Blue Line
Target Field Station Platform 1
south

这种方法的一个优点是它非常高效,不需要额外的替换或类似的东西,只需对输入进行一次迭代,仅此而已。

为了与原始答案的RegEx主题保持一致,我重写了答案以查找常规引号或智能引号。

String text = "“METRO Blue Line” “Target Field Station Platform 1” “south”";

String regex = "\"([^\"]*)\"|“([^”]*)”";

ArrayList<String> listOfStrings = new ArrayList<>();

Matcher m = Pattern.compile(regex).matcher(text);
while (m.find()) {
    if (m.group(1) != null) {
        listOfStrings.add(m.group(1));
    } 
    if (m.group(2) != null) {
        listOfStrings.add(m.group(2));
    }
}
for (String temp : listOfStrings) {
    System.out.println(temp);
}

您可以从Java 8使用String.join()。代码示例

String[] strArray = { "How", "To", "Do", "In", "Java" };
String joinedString = String.join(", ", strArray);System.out.println(joinedString);

输出:

如何,如何,在Java中运行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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