我認爲,你可以使用這個正則表達式來找到你的參數:
"(((?!").)+)"|(\S|(?<=\\)\s)+
其中給出,一旦轉錄爲Java String:
"\"(((?!\").)+)\"|(\\S|(?<=\\\\)\\s)+"
這是怎麼回事工作原理:
它匹配"(((?!").)+)"
或(\S|(?<=\\)\s)+
"(((?!").)+)"
匹配任何由"
(\S|(?<=\\)\s)+
包圍相匹配的是由什麼:
2.1。 非空格字符(\S
)或
2.2。 空格字符(\s
)如果他們是轉義(緊接在前面\
)。對於"a quoted string"
爲a\ third\ param
一次,一次anotherParam
和一次:
運行這個表達式反對:
"a quoted string" anotherParam a\ third\ param
三次匹配。
樣品測試的代碼:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
final Pattern p = Pattern.compile("\"(((?!\").)+)\"|((\\S|(?<=\\\\)\\s)+)");
final String input = "\"a quoted string\" anotherParam a\\ third\\ param";
final Matcher m = p.matcher(input);
while(m.find()) {
if(m.group(1) == null) {
System.out.println(m.group().replace("\\ ", " "));
} else {
System.out.println(m.group(1)); // trimmed from the surrounding quotes
}
}
}
}
輸出:
a quoted string
anotherParam
a third param
爲什麼'測試\文件夾somethingElse'變爲'[ 「測試文件夾」,somethingElse]'? – Maroun
因爲空間已經逃脫了。例如,如果您鍵入'mkdir test \ folder',它將創建一個名爲「test folder」的文件夾。 –
嘗試'/(?:「((\\」| [^「])*)」|((\ S | \ \)+))/'。我也建議使用解析器。 – Njol