【问题标题】:Place all text in quotes into ArrayList将引号中的所有文本放入 ArrayList
【发布时间】:2013-07-20 06:22:06
【问题描述】:

我正在寻找一种简单的方法来获取字符串并将引号中的所有值放入 ArrayList 中

例如

The "car" was "faster" than the "other"

我想要一个包含

的 ArrayList
car, faster, other

我想我可能需要为此使用 RegEx,但我想知道是否还有另一种更简单的方法。

【问题讨论】:

  • 可以有嵌套引号吗?
  • 我将解析的任何字符串中都不会有嵌套引号。

标签: java regex parsing arraylist


【解决方案1】:

使用正则表达式,实际上非常简单。注意:此解决方案假设不能有嵌套引号:

private static final Pattern QUOTED = Pattern.compile("\"([^\"]+)\"");

// ...
public List<String> getQuotedWords(final String input)
{
    // Note: Java 7 type inference used; in Java 6, use new ArrayList<String>()
    final List<String> ret = new ArrayList<>();
    final Matcher m = QUOTED.matcher(input);
    while (m.find())
        ret.add(m.group(1));
    return ret;
}

正则表达式是:

"           # find a quote, followed by
([^"]+)     # one or more characters not being a quote, captured, followed by
"           # a quote

当然,由于这是在 Java 字符串中,因此需要引用引号...因此,此正则表达式的 Java 字符串:"\"([^\"]+)\""

【讨论】:

  • 感谢代码!当我尝试使用 QUOTED 时,eclipse 抱怨 RegEx 字符串“令牌上的语法错误,删除这些令牌”
  • 呃?抱歉,我不知道您在说什么...请注意,它是私有的 static final;这意味着它必须在类级别声明,而不是在方法中。
  • 另外,代码是Java 7;查看我在编辑中添加的评论
  • 啊,是啊,我把它放错了地方。完美运行!!谢谢。
【解决方案2】:

使用此脚本解析输入:

public static void main(String[] args) {
    String input = "The \"car\" was \"faster\" than the \"other\"";
    List<String> output = new ArrayList<String>();
    Pattern pattern = Pattern.compile("\"\\w+\"");
    Matcher matcher = pattern.matcher(input);

    while (matcher.find()) {
        output.add(matcher.group().replaceAll("\"",""));
    }
}

输出列表包含:

[car,faster,other]

【讨论】:

  • OP 不想要引号
【解决方案3】:

可以使用Apache常用的String UtilssubstringsBetween方法

String[] arr = StringUtils.substringsBetween(input, "\"", "\"");
List<String> = new ArrayList<String>(Arrays.asList(arr));

【讨论】:

  • StringUtils 是什么?
  • @fge:回答您编辑的评论。我已经添加了答案的链接。
  • 好的,但是那里不需要 Apache commons ;) 注意:我不是反对者
  • @downvoter:能否请教一下奖励背后的原因?
  • @fge:我更喜欢公地(因为可能是懒惰的天性)。投反对票不是问题,只是想知道背后的原因。
猜你喜欢
  • 1970-01-01
  • 2013-07-01
  • 2022-07-21
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 2018-10-23
  • 2010-12-09
相关资源
最近更新 更多