2013-02-01 39 views
1

可能重複:
Regex for splitting a string using space when not surrounded by single or double quotes如何將字符串分解爲參數,尊重引號?

我怎樣才能打破這樣的字符串:

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

到它的參數/參數,同時尊重報價?

所以在上面的例子中,參數會被分解爲:

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

我知道如何使用拆分(」「),但我想那是在報價方面結合起來。

回答

4

假設你沒有使用正則表達式和你輸入不包含嵌套的報價,你可以在一個迭代在你的字符串中的字符實現這一點:

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"] 
0

如果你沒有引入依賴關係的問題,你可以使用Apache的Commons cli。它將簡化命令行解析並使其更加適用於用戶。

相關問題