我正在撰寫一個決議器,它將從它從檔案中讀取的一行中提取標簽和值,我想知道如何獲取該值。所以在這種情況下,我想獲取 key = "accountName" 和 value = "fname LName" 并讓它在每一行中重復。
<accountName>fname LName</accountName>
<accountNumber>12345678912</accountNumber>
<accountOpenedDate>20200218</accountOpenedDate>
這是我的代碼,這是在使用 bufferedReader 掃描每一行的 while 回圈中。我設法正確獲取密鑰,但是當我嘗試獲取值時,我得到“字串索引超出范圍 - 12。不確定如何獲取兩個箭頭之間的值 > <。
String line;
if(line.startsWith("<"){
key = line.substring(line.indexOf("<" 1, line.indexOf(">"));
value = line.substring(line.indexOf(">" 1, line.indexOf("<") 1);
}
uj5u.com熱心網友回復:
雖然建議使用 XML 決議器,但如果你想通過手動處理每一行的字串來做到這一點:(建議使用正則運算式來處理行)但是如果你想用子字串方式手動執行這里是示例:
private static void readKeyValue(String line) {
String key = null;
String value = null;
if (null != line && line.startsWith("<") && line.contains("</")) {
key = line.substring(line.indexOf("</") 2 , line.lastIndexOf(">"));
value = line.substring(line.indexOf(">") 1, line.indexOf("</"));
}
System.out.println("key: " key);
System.out.println("value: " value);
}
uj5u.com熱心網友回復:
您可以使用正則運算式進行提取,假設line變數是從每一行讀取的字串。
String pattern = "<([a-zA-Z] .*?)>([\\s\\S]*?)</[a-zA-Z]*?>";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
// find
if (m.find()) {
String key = m.group(1);
String value = m.group(2);
System.out.println("Key: " key);
System.out.println("Value: " value);
} else {
System.out.println("Invalid");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494166.html
上一篇:尋找表達方式的優雅方式
