How Split String in android containing number

Viewed 54

I have dynamic string containing number, how can I separate starting from number for example

Golden Apples Perlim 1.000 kg

I want to split Golden Apples Perlim and 1.000 kg and in Lemon 1.000 kg i want to split Lemon and 1.000 kg separably

how can i achieve this?

2 Answers

You could use a regex split:

String input = "Golden Apples Perlim 1.000 kg";
String[] parts = input.split("\\s+(?=\\d(?:\\.\\d+)?)");
for (String part : parts) {
    System.out.println(part);
}

This prints:

Golden Apples Perlim
1.000 kg

You can also use Pattern and Matcher with this regex (\D+?)(\d.*):

String[] strs = {"Golden Apples Perlim 1.000 kg", "Lemon 1.000 kg"};
Pattern pattern = Pattern.compile("(\\D+?)(\\d.*)");
Matcher matcher;
for (String str : strs) {
  matcher = pattern.matcher(str);
  if (matcher.find()){
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
  }
}

Outputs

Golden Apples Perlim 
1.000 kg
Lemon 
1.000 kg
Related