While parsing the dynamic input string using the java substring method with start and end indexes, Can we use or condition in the end index of the substring method? Meaning end index could be either ')' or ',' for my use case.
Ex: my input string have below two formats
inputformat1 : Student(name: Joe, Batch ID: 23) is updated
inputformat2 : Student(name: John, ID:0, Batch ID: 2503, Result: pass) is updated
Now I am interested to get the "Batch ID" value every-time. I wanted to achieve this by substring method. Now I'm able to get the batch id value If I use any one of the indexes ie, ')' or ','
String batchId= input.substring(input.indexOf("Batch ID: ")+9,input.indexOf(")"));
Can someone help me to the way to batch Id value basing on different end indexes?
You could use Math.min():
String batchId = input.substring(input.indexOf("Batch ID: ") + 9,
Math.min(tail_old.indexOf(")"), tail_old.indexOf(",")));
You can use regex with replaceFirst
to solve your problem for example ;
List<String> strings = Arrays.asList("Student(name: Joe, Batch ID: 23) is updated",
"Student(name: John, ID:0, Batch ID: 2503, Result: pass) is updated"
);
for (String string : strings) {
System.out.println(
string.replaceFirst(".*Batch ID:\\s+(\\d+).*", "$1")
);
}
Outputs
23
2503
If you want multiple groups you can also use Patterns like so :
Pattern pattern = Pattern.compile("name:\\s+(.*?),.*?Batch ID:\\s+(\\d+)");
Matcher matcher;
for (String string : strings) {
matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(
String.format("name : %s, age : %s", matcher.group(1), matcher.group(2))
);
}
}
Outputs
name : Joe, age : 23
name : John, age : 2503
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.