fork download
  1. import java.util.Arrays;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4.  
  5. public class Main {
  6. public static void main(String[] args) {
  7. String[] arr = { "1 years, 2 months, 22 days", "1 years, 1 months, 14 days", "4 years, 24 days",
  8. "13 years, 21 days", "9 months, 1 day" };
  9.  
  10. int[] years = new int[arr.length];
  11. int[] months = new int[arr.length];
  12. int[] days = new int[arr.length];
  13.  
  14. Pattern yearPattern = Pattern.compile("\\d+(?= year(?:s)?)");
  15. Pattern monthPattern = Pattern.compile("\\d+(?= month(?:s)?)");
  16. Pattern dayPattern = Pattern.compile("\\d+(?= day(?:s)?)");
  17.  
  18. for (int i = 0; i < arr.length; i++) {
  19. Matcher yearMatcher = yearPattern.matcher(arr[i]);
  20. Matcher monthMatcher = monthPattern.matcher(arr[i]);
  21. Matcher dayMatcher = dayPattern.matcher(arr[i]);
  22.  
  23. years[i] = yearMatcher.find() ? Integer.parseInt(yearMatcher.group()) : 0;
  24. months[i] = monthMatcher.find() ? Integer.parseInt(monthMatcher.group()) : 0;
  25. days[i] = dayMatcher.find() ? Integer.parseInt(dayMatcher.group()) : 0;
  26. }
  27.  
  28. // Display
  29. System.out.println(Arrays.toString(years));
  30. System.out.println(Arrays.toString(months));
  31. System.out.println(Arrays.toString(days));
  32. }
  33. }
Success #stdin #stdout 0.09s 49172KB
stdin
Standard input is empty
stdout
[1, 1, 4, 13, 0]
[2, 1, 0, 0, 9]
[22, 14, 24, 21, 1]