在 Java IO 中读取多个方括号值一行
Reading multiple square brackets value one line in Java IO
我有代码读取一个文件在一行中包含多个方括号 [],我将采用该值(在方括号内)并将替换为另一个字符串。问题是我只得到了行中的第一个方括号值,其他的无法处理。这是我的代码:
if (line.contains("[") && line.contains("]")) {
getindex = getIndexContent(line);
}
以及获取索引值的方法:
String getIndexContent(String str) {
int startIdx = str.indexOf("[");
int endIdx = str.indexOf("]");
String content = str.substring(startIdx + 1, endIdx);
return content;
}
这是我读到的包含方括号的文件:
var[_ii][_ee] = init_value;
好吧,我得到了_ii值,但是如何得到方括号第二个值_ee呢?我只是想象数组中的商店,但我不知道如何?
谢谢。
indexOf
接受一个可选的位置参数作为搜索的起点。如果将其设置为结束索引 endIdx
加一,它将找到第二次出现的括号。
int startIdx2 = str.indexOf("[", endIdx + 1);
int endIdx2 = str.indexOf("]", endIdx + 1);
你可以遍历你的 String
直到你得到所有
通过在一种方法中返回所有内容也让生活变得轻松:
List<String> getIndexContent(String str) {
List<String> list = new ArrayList<String>();
while(true){
if(!str.contains("[") && !str.contains("]")){
break;
}
int startIdx = str.indexOf("[");
int endIdx = str.indexOf("]");
String content = str.substring(startIdx + 1, endIdx);
list.add(content);
if(endIdx==str.length()-1){
break;
}
str=str.subString(endIdx+1,str.length());
}
return list;
}
注意:
it won't work on nested brackets
您也可以像这样使用正则表达式。
Pattern pattern = Pattern.compile("\[[^\[.]+?\]");
String str = "dt = (double[]) obj[i];";
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
您还可以获得每场比赛的第一个和最后一个索引。
matcher.start() 和 matcher.end() 将 return 当前匹配的起始索引和结束索引。
我有代码读取一个文件在一行中包含多个方括号 [],我将采用该值(在方括号内)并将替换为另一个字符串。问题是我只得到了行中的第一个方括号值,其他的无法处理。这是我的代码:
if (line.contains("[") && line.contains("]")) {
getindex = getIndexContent(line);
}
以及获取索引值的方法:
String getIndexContent(String str) {
int startIdx = str.indexOf("[");
int endIdx = str.indexOf("]");
String content = str.substring(startIdx + 1, endIdx);
return content;
}
这是我读到的包含方括号的文件:
var[_ii][_ee] = init_value;
好吧,我得到了_ii值,但是如何得到方括号第二个值_ee呢?我只是想象数组中的商店,但我不知道如何?
谢谢。
indexOf
接受一个可选的位置参数作为搜索的起点。如果将其设置为结束索引 endIdx
加一,它将找到第二次出现的括号。
int startIdx2 = str.indexOf("[", endIdx + 1);
int endIdx2 = str.indexOf("]", endIdx + 1);
你可以遍历你的 String
直到你得到所有
通过在一种方法中返回所有内容也让生活变得轻松:
List<String> getIndexContent(String str) {
List<String> list = new ArrayList<String>();
while(true){
if(!str.contains("[") && !str.contains("]")){
break;
}
int startIdx = str.indexOf("[");
int endIdx = str.indexOf("]");
String content = str.substring(startIdx + 1, endIdx);
list.add(content);
if(endIdx==str.length()-1){
break;
}
str=str.subString(endIdx+1,str.length());
}
return list;
}
注意:
it won't work on nested brackets
您也可以像这样使用正则表达式。
Pattern pattern = Pattern.compile("\[[^\[.]+?\]");
String str = "dt = (double[]) obj[i];";
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
您还可以获得每场比赛的第一个和最后一个索引。 matcher.start() 和 matcher.end() 将 return 当前匹配的起始索引和结束索引。