You can do it in different manner.
One of the simplest in this case is split the string and getting the fifth and ninth element
String sentence = "The data of Branch 1 are correct - true";
String[] elements = string.split(" "); then get relevant elements of array.
// elements[4] is the string 1 (you can convert it to int if necessary with Integer.parseInt(elements[4]) )
// elements[8] is the string true (you can convert it to boolean if necessary with Boolean.parseBoolean(elements[4]) )
Other possibilities are:
- Using regular expressions (find the number and search the words true false)
- Using the position (you know that the number starts always in the same position and that the boolean value is always at the end)
Knowing that you can create a method similar to the following to print the relevant parts:
public static void printRelevant(String string) {
String[] elements = string.split(" ");
System.out.println(elements[4] + " " + elements[8]);
}
...
pritnRelevant("The data of Branch 1 are correct - true");
printRelevant("The data of Branch 4 are correct - false");
Thanks to the comments of Sotirios I saw that the 2 phrases are not equals.
So it is necessary to use a regular expression to extract the relevant parts:
public static void printRelevant(String string) {
Pattern numberPattern = Pattern.compile("[0-9]+");
Pattern booleanPattern = Pattern.compile("true|false");
Matcher numberMatcher = numberPattern.matcher(string);
Matcher booleanMatcher = booleanPattern.matcher(string);
if (numberMatcher.find() && booleanMatcher.find()) {
return numberMatcher.group(0) + " " + booleanMatcher.group(0);
}
throw new IllegalArgumentException("String not valid");
}