我一直困在一个问题,我从文件中逐行读取并将这些行作为字符串存储在arrayList中。然后循环访问该列表以查找在“ring =”之后出现的int我使用的模式是“(?< = rings =)[0-9] {1}”我在下面的代码中有一个print语句告诉我这个int但它永远不会被使用意味着该方法可能找不到int。从中获取int的示例是。
//Event=ThermostatDay,time=12000
//Event=Bell,time=9000,rings=5
//Event=WaterOn,time=6000
代码是
for (int i = 0; i < fileToArray.size(); i++) {
try {
String friskForX = fileToArray.get(i).toString();
Matcher xTimeSeeker = rinngerPat.matcher(friskForX);
if (xTimeSeeker.group() != null) {
System.out.println("will ring more then once ");
xTimesRing = xTimeSeeker.group();
int xTimeSeekerInt = Integer.parseInt(xTimesRing);
System.out.println(xTimeSeekerInt);
}
}
//this catches it but does nothing since some files might not have x value.
catch (IllegalStateException e) { }
}
答案 0 :(得分:0)
将您的模式更改为:.*rings=(\\d+).*
String pattern=".*rings=(\\d+).*";
Pattern rinngerPat = Pattern.compile(pattern);
然后group(1)
会有你的数字
for(String line : fileToArray) {
Matcher xTimeSeeker = rinngerPat.matcher(line);
if(xTimeSeeker.find()) {
xTimesRing = xTimeSeeker.group(1);
int xTimeSeekerInt = Integer.parseInt(xTimesRing);
System.out.println(xTimeSeekerInt);
}
}
自包含的例子:
public static void main(String[] args) {
List<String> fileToArray = new ArrayList<>();
fileToArray.add("Event=ThermostatDay,time=12000");
fileToArray.add("Event=Bell,time=9000,rings=5");
fileToArray.add("Event=WaterOn,time=6000");
String pattern=".*rings=(\\d+).*";
Pattern rinngerPat = Pattern.compile(pattern);
String xTimesRing;
for(String line : fileToArray) {
Matcher xTimeSeeker = rinngerPat.matcher(line);
if(xTimeSeeker.find()) {
xTimesRing = xTimeSeeker.group(1);
int xTimeSeekerInt = Integer.parseInt(xTimesRing);
System.out.println(xTimeSeekerInt);
}
}
}