Search code examples
javastringsubstring

Java: Getting a substring from a string starting after a particular String


I have a string:

CLAIM NUMBER 1234563 AND INCIDENT DATE 12/12/2020 12:00:00 

I would like to extract 1234563 and 12/12/2020 12:00:00 from this, i.e. the substring after the NUMBER and DATE.

Could someone please provide some help?

I tried though the the substring and index but it's not giving expected answer.


Solution

  • It is better to use regexp to extract data from formatted string.

    final String regex = "CLAIM NUMBER\\s+(?<claimNumber>\\S+)\\s+AND INCIDENT DATE\\s+(?<incidentDate>\\S+\\s+\\S+)";
    final String str = "CLAIM NUMBER 1234563 AND INCIDENT DATE 12/12/2020 12:00:00";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);
    
    if(matcher.matches()) {
        String claimNumber = matcher.group("claimNumber");
        String incidentDate = matcher.group("incidentDate");
    }