0

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

例如

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

我想要一个 ArrayList 包含

car, faster, other

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

4

3 回答 3

2

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

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 字符串:"\"([^\"]+)\""

于 2013-07-20T06:25:01.230 回答
1

使用此脚本解析输入:

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]
于 2013-07-20T06:27:46.380 回答
0

可以使用 Apache 常用的 String Utils substringsBetween方法

String[] arr = StringUtils.substringsBetween(input, "\"", "\"");
List<String> = new ArrayList<String>(Arrays.asList(arr));
于 2013-07-20T06:28:21.003 回答