[英]How can I allow quoted data in a split?
我正在研究一個可以測量兩個城市之間距離的項目。 我正在嘗試設置它,以便用戶輸入一個命令行命令來搜索兩個城市,例如“距離達拉斯紐約市”。 現在,我有了它,可以使用.split()方法將行拆分為字符串數組,但是會在空格和標點符號上進行拆分,這意味着名稱超過一個單詞的城市將無法使用。 理想情況下,我希望它能正常工作,以便鍵入“ Dallas Dallas”(紐約市)“距離”,但我不確定如何執行此操作。
public static void main(String[] args) {
CSVReader reader = new CSVReader();
Scanner in = new Scanner(System.in);
LinkedList[] entries = new LinkedList[14089];
boolean running = true;
reader.run("cities.csv", entries);
while(running){
String[] arg = in.nextLine().split("[,;:\\.\\s]+");
if(arg[0].equals("retrieve")){
search(arg[1], entries);
System.out.println();
}
if(arg[0].equals("distance")){
distance(arg[1], arg[2], entries);
System.out.println();
}
if(arg[0].equals("stop")){
stop(entries);
running = false;
}
}
}
}
也許你可以使用這個:
String task = "distance: Dallas, New York City";
System.out.println(task.split(":|,")[0]);// return "distance"
System.out.println(task.split(":|,")[1]);// return " Dallas"
System.out.println(task.split(":|,")[2]);// return " New York City"
如果您使用java.util.regex
的Pattern
和Matcher
,則可以使用諸如".*?"|\\S+
類的正則表達式對輸入進行標記化,然后可以在多詞城市周圍使用引號。 Regex101經過測試
首先在代碼開頭編譯正則表達式:
final Pattern p = Pattern.compile("\".*?\"|\\S+");
然后生成這樣的arg
:
String[] arg = new String[3];
Matcher m = p.matcher(in.nextLine());
for (int i = 0; i < arg.length && m.find(); i++) {
arg[i] = m.group().replace("\"", "");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.