如何在尊重引号的情况下将字符串分解为参数? [英] How do I break a string into arguments, respecting quotes?

查看:60
本文介绍了如何在尊重引号的情况下将字符串分解为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
正则表达式,用于拆分当字符串不被单引号或双引号引起来时使用空格

如何中断这样的字符串:

How can I break a string like this:

String args = "\"file one.txt\" filetwo.txt some other \"things here\"";

在遵守引号的同时添加其参数/参数?

into its arguments / parameters while respecting quotes?

因此,在上面的示例中,参数将被分解为:

So in the above example, the arguments would be broken into:

args[0] = file one.txt
args[1] = filetwo.txt
args[2] = some
args[3] = other
args[4] = things here

我知道如何使用split("),但是我想合并引号中的术语.

I understand how to use split(" "), but I want to combine terms that are in quotes.

推荐答案

假设您不必使用正则表达式,并且您的输入不包含嵌套引号,则可以在一次迭代中实现在您的String字符上:

Assuming that you don't have to use regex and your input doesn't contains nested quotes you can achieve this in one iteration over your String characters:

String data = "\"file one.txt\" filetwo.txt some other \"things here\"";

List<String> tokens = new ArrayList<String>();
StringBuilder sb = new StringBuilder();

boolean insideQuote = false;

for (char c : data.toCharArray()) {

    if (c == '"')
        insideQuote = !insideQuote;

    if (c == ' ' && !insideQuote) {//when space is not inside quote split..
        tokens.add(sb.toString()); //token is ready, lets add it to list
        sb.delete(0, sb.length()); //and reset StringBuilder`s content
    } else 
        sb.append(c);//else add character to token
}
//lets not forget about last token that doesn't have space after it
tokens.add(sb.toString());

String[] array=tokens.toArray(new String[0]);
System.out.println(Arrays.toString(array));

输出:

["file one.txt", filetwo.txt, some, other, "things here"]

这篇关于如何在尊重引号的情况下将字符串分解为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆