[英]Java: Getting a substring from a string ending before a particular character
[英]Getting substring of a string that has a repeating character Java
我正在编写一个解析器,它将从它从文件中读取的一行中提取标签和值,我想知道如何获取该值。 所以在这种情况下,我想获取 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);
}
虽然建议使用 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);
}
您可以使用正则表达式进行提取,假设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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.