简体   繁体   中英

Finding the 1st and 2nd occurrence of a regex in a string in Java

If I have a string such as

First timing is 10:10:30, second timing is 11:12:45, third is 12:14:25

How do I get only the first and second occurrence of timing that is formatted to show only the minutes and seconds?

The end result should be 2 strings for example,

string1 = 10:10
string2 = 11:12

Thank you.

 var regEx = /timing[^\\d]+(\\d+:\\d+)/ig; var text = 'First timing is 10:10:30, second timing is 11:12:45, third is 12:14:25' var match = regEx.exec(text); while(match !== null) { console.log(match[1]); match = regEx.exec(text); }

  public static void main(String[] args) {
    String myString = "First timing is 10:40:30, second timing is 11:12:45, 
    third is 12:14:25";
    myString = myString.replaceAll("[a-zA-z]","");
    String[] numbers = myString.trim().split("\\s*,\\s*");
    for(int i=0;i<numbers.length;i++){
             System.out.println("string"+(i+1)+" = "+numbers[i].substring(0,numbers[i].length()-3));     
    }

}

Output
string1 = 10:40 string2 = 11:12 string3 = 12:14

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.

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