繁体   English   中英

在Java中使用引号之间的值拆分字符串

[英]Splitting a string by value between quotation marks in Java

我正在读取Java中的文件,并希望将每行除以引号内的值。 例如,一条线将是......

“100”,“this,is”,“a”,“test”

我希望数组看起来像..

[0] = 100
[1] = this, is
[2] = a
[3] = test

我通常用逗号分隔,但由于某些字段包含逗号(上例中的位置1),因此不太合适。

谢谢。

您可以通过以下方式拆分它:

String input = "\"100\",\"this, is\",\"a\",\"test\"";
for (String s:input.split("\"(,\")*")) {
    System.out.println(s);
}

产量

100
this, is
a
test

注意第一个数组元素将为空。

这是一个简单的方法:

String example = "\"test1, test2\",\"test3\"";
int quote1, quote2 = -1;
while((quote2 != example.length() - 1) && quote1 = example.indexOf("\"", quote2 + 1) != -1) {
  quote2 = example.indexOf("\"", quote1 + 1);
  String sub = example.substring(quote1 + 1, quote2); // will be the text in your quotes
}

您可以执行以下操作

    String yourString = "\"100\",\"this, is\",\"a\",\"test\"";
    String[] array = yourString.split(",\"");
    for(int i = 0;i<array.length;i++)
        array[i] = array[i].replaceAll("\"", "");

最后, 数组变量将是所需的数组

输出:

    100
    this, is
    a
    test

这是一种使用正则表达式的方法。

public static void main (String[] args) {
    String s = "\"100\",\"this, is\",\"a\",\"test\"";
    String arr[] = s.split(Pattern.quote("\"\\w\"")));
    System.out.println(Arrays.toString(arr));
}

输出:

["100","this, is","a","test"]

它的作用是匹配:

 \" -> start by a "
  \\w -> has a word character
  \" -> finish by a "

我不知道你有什么样的价值观,但你可以根据需要修改它。

快速又脏,但有效:

    String s = "\"100\",\"this, is\",\"a\",\"test\"";
    StringBuilder sb  = new StringBuilder(s);
    sb.deleteCharAt(0);
    sb.deleteCharAt(sb.length()-1);
    String [] buffer= sb.toString().split("\",\"");
    for(String r : buffer)
        System.out.println(r); code here

暂无
暂无

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

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