簡體   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