2017-07-07 39 views
0

我正在製作一個TeamSpeak3 ServerQuery bot,命令行樣式。我已經下了命令,但是我似乎無法將我的頭包裹起來,這是命令的參數。我使用reset()方法創建參數列表,因此組合字符串會更容易。結合使用雙引號的參數

例如,假設我改變內存設置爲我的機器人的名字

set query name "Kyles Bot" 

但該方案以「Kyles和機器人」作爲兩個不同的參數。我希望他們是一個整體。我會如何去做這件事?復位所需

字段():

// Keep String[] and 3 strings null for now, they'll be changed. 
private String command, to1, to2; 
private String[] to3; 
private List<String> args = new ArrayList<>(); 

復位()方法:

private void reset() { 
      args.clear(); 
      to1 = line.getText(); 
      command = to1.split(" ")[0]; 
      if (to1.split(" ").length > 1) { 
       to2 = to1.substring(command.length() + 1, to1.length()); 
       to3 = to2.split(" "); 
       for (int i = 0; i < to3.length; i++) { 
        if (to3[i].isEmpty() || to3[i].startsWith(" ")) { 
         System.out.println("Argument null, command cancelled. [" + to3[i] + "]"); 
         break; 
        } else { 
         args.add(to3[i]); 
        } 
       } 
       //EDIT2: Removed useless for loop, 
       //it was my previous attempt to solve the problem. 
      } else { 
       //EDIT: This loop here is used to prevent AIOUB 
       command = to1; 
       for (int i = 0; i < 5; i++) { 
        args.add("NullElement"); 
       } 
      } 
     } 
+0

'設置查詢名稱「Kyles Bot」'這看起來很可疑。你是否得到一個環境變量?他們不能包含空格。嘗試'設置查詢名稱「Kyles Bot」' – Michael

+0

否@Michael,這些命令與我在另一個類中使用的HashMap進行交互。對不起,如果不明確。如果您願意,我會在課堂上發佈該課程。 – FlashDaggerX

+0

這已經是相當長的代碼示例,所以不要這樣做。我懷疑你的大部分代碼與這個特定的問題沒有關係。請創建一個[Minimal,Complete和Verifiable示例](https://stackoverflow.com/help/mcve) - 基本刪除*不相關的所有*,並確保您發佈的代碼能夠在其上運行如果我們將其複製並粘貼到IDE,那麼它就是自己的。如果你這樣做,我會確保要麼解決你的問題,要麼提高獎金,這樣別人就會。 – Michael

回答

1

問題是這樣的線:

to3 = to2.split(" "); 

它分割所述讀取命令每個空間,包括引用文本中的空格。

你需要在命令行中使用正則表達式正確拆分,例如:

// matches either a "quoted string" or a single word, both followed by any amount of whitespace 
    Pattern argumentPattern = Pattern.compile("(\"([^\"]|\\\")*\"|\\S+)\\s*"); 

    // loop over all arguments 
    Matcher m = argumentPattern.matcher(to2); 
    for (int start = 0; m.find(start); start = m.end()) { 

     // get a single argument and remove whitespace around it 
     String argument = m.group(1).trim(); 

     // handle quoted arguments - remove outer quotes and unescape inner ones 
     if (argument.startsWith("\"")) 
      argument = argument.substring(1, argument.length() - 1).replace("\\\"", "\""); 

     // ... your code that uses the argument here 

    } 

請注意,這不是一個命令行分析器的完整實現 - 如果你收到任意命令,你應該看看爲你解析的庫,並能正確處理所有的細節。

PS:請使用描述性變量名稱而不是to1, to2, to3等,例如我在我的代碼中使用了argument而不是to3

+0

我甚至不知道模式存在,感謝您的建議!我會在第二個測試 – FlashDaggerX

+0

@KyleTheHacker我剛剛修復了代碼中的一個錯誤,您需要使用新版本進行測試(循環和第一行不同,現在不同,其餘部分都是一樣的) – Njol

+0

好吧。我也會解決這個問題。 – FlashDaggerX