fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.regex.*;
  4. import java.lang.*;
  5. import java.time.*;
  6. import java.time.format.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. private static DateTimeFormatter DMY = new DateTimeFormatterBuilder()
  12. .appendOptional(DateTimeFormatter.ofPattern("dd-MM[-uuuu]"))
  13. .appendOptional(DateTimeFormatter.ofPattern("dd/MM[/uuuu]"))
  14. .toFormatter().withResolverStyle(ResolverStyle.STRICT);
  15. /* outra opção seria
  16.   new DateTimeFormatterBuilder()
  17.   .optionalStart()
  18.   .appendPattern("dd-MM[-uuuu]")
  19.   .optionalEnd()
  20.   .optionalStart()
  21.   .appendPattern("dd/MM[/uuuu]")
  22.   .optionalEnd()
  23.   .toFormatter().withResolverStyle(ResolverStyle.STRICT);
  24.   */
  25. private static Pattern POSSIBLE_DATE_REGEX = Pattern.compile("\\b\\d{2}[-/]\\d{2}([-/]\\d{4})?\\b");
  26.  
  27. static String getDate(String text) {
  28. Matcher matcher = POSSIBLE_DATE_REGEX.matcher(text);
  29. if (matcher.find()) { // se encontrou, valida a data
  30. String possivelData = matcher.group();
  31. try {
  32. DMY.parseBest(possivelData, LocalDate::from, MonthDay::from);
  33. } catch (DateTimeParseException e) {
  34. // data inválida (se quiser, imprima o erro: System.out.println("Erro: " + e.getMessage());
  35. return null;
  36. }
  37. return possivelData;
  38. }
  39.  
  40. // se não encontrou, retorna null
  41. return null;
  42. }
  43.  
  44. public static void main (String[] args) throws java.lang.Exception
  45. {
  46. final String text1 = "Foo bar foo bar foo bar 29/01/2021 foo bar foo bar";
  47. final String text2 = "Foo bar foo bar 29-01-2021 foo bar foo bar";
  48. final String text3 = "Foo bar foo bar 29/01 foo bar foo bar";
  49. final String text4 = "Foo bar foo bar 29-01 foo bar foo bar";
  50.  
  51. System.out.println(getDate(text1)); // 29/01/2021
  52. System.out.println(getDate(text2)); // 29-01-2021
  53. System.out.println(getDate(text3)); // 29/01
  54. System.out.println(getDate(text4)); // 29-01
  55. System.out.println(getDate("29.12"));
  56. }
  57. }
Success #stdin #stdout 0.12s 35344KB
stdin
Standard input is empty
stdout
29/01/2021
29-01-2021
29/01
29-01
null