这是我的字符串
“ / opt / jboss-eap / bin / jboss-cli.sh --connect --controller = localhost:9990 -c命令= \“部署/app/jboss-eap-7.1/standalone/updates/sample.war --force \”“
我想按如下方式分割上面的字符串
/opt/jboss-eap/bin/jboss-cli.sh
--connect
--controller=localhost:9990
-c
command="deploy /app/jboss-eap-7.1/standalone/updates/sample.war --force"
我尝试使用以下代码
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Matcher regexMatcher = regex.matcher("/opt/jboss-eap/bin/jboss-cli.sh --connect --controller=localhost:9990 -c command=\"deploy /app/jboss-eap-7.1/standalone/updates/sample.war --force\"");
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
out.println("matchList="+matchList);
但是输出是
matchList = [/ opt / jboss-eap / bin / jboss-cli.sh,--connect, --controller = localhost:9990,-c,command =,“部署/app/jboss-eap-7.1/standalone/updates/sample.war --force”]
/opt/jboss-eap/bin/jboss-cli.sh
--connect
--controller=localhost:9990
-c
command=
"deploy /app/jboss-eap-7.1/standalone/updates/sample.war --force"
适用于Java' ProcessBuilder '
我从此链接Tokenizing a String but ignoring delimiters within quotes使用了另一种方法
String str = "/opt/jboss-eap/bin/jboss-cli.sh --connect --controller=localhost:9990 -c command=\"deploy /app/jboss-eap-7.1/standalone/updates/sample.war --force\"";
String regex = "\"([^\"]*)\"|(\\S+)";
List<String> list = new ArrayList<String>();
Matcher m = Pattern.compile(regex).matcher(str);
while (m.find())
{
if (m.group(1) != null)
{
list.add(m.group(1));
}
else
{
list.add(m.group(2));
}
}
out.println(list);
输出为
/opt/jboss-eap/bin/jboss-cli.sh
--connect
--controller=localhost:9990
-c
command="deploy
/app/jboss-eap-7.1/standalone/updates/sample.war
--force"
答案 0 :(得分:0)
只需使用带有多个定界符的String split#method。
String string = "/opt/jboss-eap/bin/jboss-cli.sh --connect --controller=localhost:9990 -c command=\"deploy /app/jboss-eap-7.1/standalone/updates/sample.war --force\";
String[] parts = string.split("((-c)|(\\--))");
String part1 = parts[0];
String part2 = parts[1];
以此类推。这样,您还将分隔符保留在字符串部分中。