【问题标题】:How to get string from several double quotes in a line?如何从一行中的几个双引号中获取字符串?
【发布时间】:2017-05-01 17:31:23
【问题描述】:

基本上,我需要得到a b c(单独)

从一行开始(每个“”之间有任意数量的空格

"a" "b" "c"

是否可以使用 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
}

【问题讨论】:

  • 您还希望输出为a b c 而不是"a" "b" "c" 正确吗?
  • @brso05 我已经尝试了从 split(".*?\".*?") 到 ("\\s*\"\\s*") 的所有方法。后者有效,但它将数据拆分为数组的每个其他索引(1、3、5),其他索引为空“”。
  • 看起来你想replace all " 使用空字符串
  • @brso05 正确,没有引号。
  • 如果您在\"([a-z])\" 上进行模式匹配怎么办?

标签: java regex string


【解决方案1】:

您可以改用模式:

String str = "\"a\" \"b\" \"c\" \"\"";
Pattern pat = Pattern.compile("\"[a-z]+\"");
Matcher mat = pat.matcher(str);

while (mat.find()) {
    System.out.println(mat.group());
}

对于像 "a" "b" "c" "" 这样的输入,然后是:

输出

"a"
"b"
"c"

如果你想得到不带引号的 b c,你可以使用:

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));
}

输出

a
b
c

带空格的字符串

如果引号之间可以有空格,则可以使用\"([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));
}

输出

a
b
c include spaces

Ideone

【讨论】:

    【解决方案2】:

    在拆分字符串之前,您需要先进行替换,例如“a”   “b” “c” 到 “a” “b” “c”。 String myLetters[] = myString.replaceAll("\\s*"," ").split(" ") 应该通过两个步骤:

    1. 将所有空格\s* 替换为单个空格
    2. Split将字符串根据单个空格分片

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多