Extract a date from a string in Java

3

I'm trying to extract the date from a string that can come in different formats such as:

Cod. principal: 785369-06 Fecha 14/10/2015

And even things after the date, such as:

Fecha 2015-11-24 asddsa12 Otros datos: 12202

How could I do to extract 14/10/2015 from this String?

Is not there a regular expression that allows me to take everything that is after "Date"? Or some other type of solution.

Thank you very much!

    
asked by Genarito 05.01.2017 в 01:20
source

4 answers

3

There I managed to solve it without external libraries:

private static boolean obtenerFecha(String palabra) {
    // Se fija si hace match con algun formato de fecha conocido
    Matcher m = Pattern.compile("([0-9]{2}(/|-|.)[0-9]{2}(/|-|.)[0-9]{4})|([0-9]{4}(/|-|.)[0-9]{2}(/|-|.)[0-9]{2})").matcher(palabra);
    if (m.find()) {
        System.out.println("Encontrada la fecha!! --> " + m.group(0) + "\n");
        return true;
    }
    return false;
}

You simply get all matches matcher() and return them with group()

    
answered by 05.01.2017 / 03:16
source
3
String texto = "Cod. principal: 785369-06 Fecha 14/10/2015";
//split crea una lista de elementos separados por la palabra "Fecha"
String[] texto_split = texto.split("Fecha"); 
// se elige el segmento 1 y se hace trim para quitar el espacio
String fecha = texto_split[1].trim();
    
answered by 05.01.2017 в 01:26
2

You can use the function split . This function would create an array taking as reference the word you indicate.

For your example you could use:

String string = "Cod. principal: 785369-06 Fecha 14/10/2015";
/* Divide tu string en partes tomando como referencia el string " Fecha " y lo almacena 
en un array */
String[] stringArray = string.split(" Fecha ");

System.out.println(stringArray[1]); //Devolverá 14/10/2015
    
answered by 05.01.2017 в 01:25
0

To do this you can use the natty library: link

What would work for the 2 cases:

case a)

import com.joestelmach.natty.*;

List<Date> dates = new Parser().parse("Cod. principal: 785369-06 Fecha 12/10/2015").get(0).getDates();
System.out.println("Fecha: " + dates.get(0));

case b)

List<Date> dates = new Parser().parse("Fecha 2015-11-24 asddsa12 Otros datos: 12202").get(0).getDates();
System.out.println("Fecha: " + dates.get(0));

Even to search several dates in the same chain:

List<Date> dates = new Parser().parse("Cod. principal: 785369-06 Fecha 12/10/2015 Fecha 2015-11-24 asddsa12 Otros datos: 12202").get(0).getDates();
System.out.println("Fecha1: " + dates.get(0));
System.out.println("Fecha2: " + dates.get(1));

Another option is as comrades comment through split ().

String texto = "Cod. principal: 785369-06 Fecha 14/10/2015";
String[] array_split = texto.split("Fecha"); 
String myFecha = array_split[1].trim();
    
answered by 05.01.2017 в 02:08