繁体   English   中英

Java子串方法中的OR条件

[英]OR condition in java substring method

在使用带有起始和结束索引的java子字符串方法解析动态输入字符串时,我们可以在子字符串方法的结束索引中使用或条件吗? 在我的用例中,最终索引可以是')'或','。

例如:我的输入字符串具有以下两种格式

inputformat1 : Student(name: Joe, Batch ID: 23) is updated
inputformat2 : Student(name: John, ID:0, Batch ID: 2503, Result: pass) is updated

现在,我有兴趣每次获取“批次ID”值。 我想通过子字符串方法实现这一点。 现在,我可以获取批次ID值,如果我使用任何一个索引,即')'或','

String batchId= input.substring(input.indexOf("Batch ID: ")+9,input.indexOf(")")); 

有人可以帮助我根据不同的最终指标来批量分配ID值吗?

您可以使用Math.min():

String batchId = input.substring(input.indexOf("Batch ID: ") + 9,
                     Math.min(tail_old.indexOf(")"), tail_old.indexOf(",")));

例如,可以将regex与replaceFirst一起使用来解决问题;例如,

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")
    );
}

输出

23
2503

如果要多个组,也可以使用Patterns,如下所示:

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))
        );
    }
}

输出

name : Joe, age : 23
name : John, age : 2503

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM