[英]Split Java string with quotes into args with no quotes
我需要將我的字符串分成3個arg ,每個arg都是引號內的內容,並將它們存儲在單獨的變量中。
這就是我所擁有的。 下面的代碼接受所有命令行參數,並將它們組合為一個大String
。
我需要轉換的字符串示例:
“METRO Blue Line” “Target Field Station Platform 1” “south”
它應該變成:
var1 = METRO Blue Line
var2 = Target Field Station Platform 1
var3 = south
我已經對split("\\"")
進行了很多嘗試,但是無論出於什么原因,它甚至都沒有為我刪除引號。
// Construct a string to hold the whole args.
// Implemented it this way because args is separated by spaces
String combine = "";
for(int i = 0; i < args.length; i++)
{
combine = combine.concat(args[i]);
combine = combine.concat(" ");
}
System.out.println(combine);
您正在使用彎曲的引號(也稱為智能引號)標記,而不是在代碼中進行說明
Pattern pattern = Pattern.compile("[“”]");
String text = "“METRO Blue Line” “Target Field Station Platform 1” “south” ";
String arr[] = text.split("\\”");
for (int i = 0; i < arr.length; i++) {
System.out.println(pattern.matcher(arr[i]).replaceAll("").trim());
}
符號”
和“
不同於符號"
。如果使用split("\\"")
進行split("\\"")
,則顯然可以搜索"
但不能搜索其他引用符號”
和“
。
您可以使用Matcher
及其find
方法輕松提取它們。 或者使用正確的分隔符使用splitting方法: split("” “")
。 請注意,第一個和最后一個元素將帶有單引號,只需將其刪除即可。
String input = "“METRO Blue Line” “Target Field Station Platform 1” “south”";
String[] elements = input.split("” “");
// Remove first quote
elements[0] = elements[0].substring(1);
// Remove last quote
String lastElement = elements[elements.length - 1];
elements[elements.length - 1] = lastElement.substring(0, lastElement.length() - 1);
// Output all results
for (String element : elements) {
System.out.println(element);
}
輸出為:
METRO Blue Line
Target Field Station Platform 1
south
這種方法的一個優點是它非常高效,不需要額外的替換或類似的東西,只需對輸入進行一次迭代,僅此而已。
為了與原始答案的RegEx主題保持一致,我重寫了答案以查找常規引號或智能引號。
String text = "“METRO Blue Line” “Target Field Station Platform 1” “south”";
String regex = "\"([^\"]*)\"|“([^”]*)”";
ArrayList<String> listOfStrings = new ArrayList<>();
Matcher m = Pattern.compile(regex).matcher(text);
while (m.find()) {
if (m.group(1) != null) {
listOfStrings.add(m.group(1));
}
if (m.group(2) != null) {
listOfStrings.add(m.group(2));
}
}
for (String temp : listOfStrings) {
System.out.println(temp);
}
您可以從Java 8使用String.join()。代碼示例
String[] strArray = { "How", "To", "Do", "In", "Java" };
String joinedString = String.join(", ", strArray);System.out.println(joinedString);
輸出:
如何,如何,在Java中運行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.