You can do the following:
- We divide the entire line using
"Number = " as a separator. - In each resulting substring of the form
"1 Vasya" we take the part up to the space and convert it to Integer . - We put this all into an array.
Code:
// ΠΠ°Ρ ΡΠ΅ΠΊΡΡ String text = "Number = 1 Vasya Number = 2 Valera Number = 3 Kolya"; // ΠΠ΅Π»ΠΈΠΌ Π΅Π³ΠΎ, ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΡ ΡΠ°Π·Π΄Π΅Π»ΠΈΡΠ΅Π»Ρ String substrings[] = text.split("Number\\s*=\\s*"); // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΏΡΡΡΡΡ ΠΊΠΎΠ»Π»Π΅ΠΊΡΠΈΡ ArrayList<Integer> arrayList = new ArrayList<>(); // ΠΡΠΎΡ
ΠΎΠ΄ΠΈΠΌΡΡ ΠΏΠΎ ΠΏΠΎΠ»ΡΡΠΈΠ²ΡΠΈΠΌΡΡ ΠΏΠΎΠ΄ΡΡΡΠΎΠΊΠ°ΠΌ for (int i = 1; i < substrings.length; ++i) { String str = substrings[i]; arrayList.add(new Integer(str.substring(0, str.indexOf(' ')))); } // ΠΡΠ²ΠΎΠ΄ΠΈΠΌ arrayList Π½Π° ΡΠΊΡΠ°Π½ arrayList.forEach(System.out::println); // ΠΡΠ»ΠΈ Π½ΡΠΆΠ½ΠΎ ΠΏΠΎΡΠ»Π΅ ΡΠΎΠ·Π΄Π°ΡΡ ΠΌΠ°ΡΡΠΈΠ² ΠΏΡΠΈΠΌΠΈΡΠΈΠ²ΠΎΠ²: int numbers[] = new int[arrayList.size()]; for (int i = 0; i < numbers.length; ++i) { numbers[i] = arrayList.get(i); }
I used "Number\\s*=\\s*" as a separator so that everything works, even if you have no spaces before the = sign or after, or there are several of them.
Here it is:
new Integer(str.substring(0, str.indexOf(' ')))
We take one of the substrings, and "rip out" a part of it from the very beginning to the first space. After we create an Integer instance using a constructor that takes a string as a parameter.
We are going through the cycle, starting from substring 1 , since null will either be empty or contain the text preceding the Number... we Number... .
And further. If you want to make something more universal in order to find such occurrences in different places of arbitrary text, then you need to use more complex regular expressions that you are unlikely to just take and write. So learn the theory about regulars ...