2013-03-07 43 views
1

請幫忙寫一個模式來僅在說謊的命令及其參數之間的空間在命令行拆分:Java。寫模式,以命令行拆分,以空白

我的代碼:

String commands = "gedit /home/ant/Documents/Txt Books/1.txt /home/ant/Documents/1.txt"; 

String[] arrCommands = Pattern.compile("\\\s[^\\\s\\\w]").split(commands); 

for (int i = 0; i < arrCommands.length; i++) { 
    System.out.println(arrCommands[i]); 
} 

程序會產生以下結果:

的gedit
家/ ANT /文檔/ TXT書籍/ 1.txt的
家/ ANT /文檔/的1.txt

,這是必要的,使之如此:

的gedit
/家庭/ ANT /文檔/ TXT書籍/ 1.txt的
/home/ant/Documents/1.txt

回答

0

您需要使用這個表達式拆分

\\s+(?=[^\\w\\s]) 

在您的正則表達式[^\\\s\\\w] space..hence結果後會吃第一字符..

使用lookahead這是隻檢查的模式,但不會吃它...

+0

謝謝你,這個模式使得應該是什麼。 – Wayne 2013-03-07 08:54:23

1

你也可以嘗試使用分裂分裂STRING()方法

例如:

請幫忙寫一個模式來分割命令行只在命令和它的參數之間的空格:

String commands = "gedit /home/ant/Documents/Txt Books/1.txt /home/ant/Documents/1. 
String[] commandsToArray=commands.split("\\s+");//this wil ignore multiples whitespaces 
+0

結果的gedit 家/ ANT /文檔/ TXT書籍/ 1.txt的 家/ ANT /文檔/的1.txt – Wayne 2013-03-07 08:47:24

+0

需要:gedit中 /家庭/ ANT /文檔/ TXT書籍/ 1.txt的 /家庭/ ANT/Documents/1.txt – Wayne 2013-03-07 08:48:36

+0

只需使用'commands.split(「」)'?爲我工作...... – fgysin 2013-03-07 09:26:14