1

请帮助编写一个模式以仅在命令及其参数之间的空格上拆分命令行:

我的代码:

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
home/ant/Documents/Txt Books/1.txt
home/ant/Documents/1.txt

并且有必要这样做:

gedit
/home/ant/Documents/Txt Books/1.txt
/home/ant/Documents/1.txt

4

2 回答 2

1

您也可以尝试使用 split() 方法拆分字符串

例如 :

请帮助编写一个模式以仅在命令及其参数之间的空格上拆分命令行:

String commands = "gedit /home/ant/Documents/Txt Books/1.txt /home/ant/Documents/1.
String[] commandsToArray=commands.split("\\s+");//this wil ignore multiples whitespaces
于 2013-03-07T08:42:56.733 回答
0

您需要使用此正则表达式来拆分

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

在你的正则表达式[^\\\s\\\w]中会吃空格后的第一个字符..因此结果..

使用lookahead它只会检查模式但不会吃掉它......

于 2013-03-07T08:37:14.787 回答