Home > Software design >  Java: Getting a substring from a string starting after a particular String
Java: Getting a substring from a string starting after a particular String

Time:10-28

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.

CodePudding user response:

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

CodePudding user response:

If the text is always the same, then you can do that with String#substring().

String data = "CLAIM NUMBER 1234563 AND INCIDENT DATE 12/12/2020 12:00:00 ";
String number = data.substring(13, 20);
String datetime = data.substring(39, 58);
System.out.println(number   ", "   datetime);
// output: 1234563, 12/12/2020 12:00:00
  • Related