¿Cómo puedo extraer un patrón de fecha y hora de cualquier cadena en Java?

¿Cómo puedo extraer un patrón de fecha y hora de cualquier cadena en Java?

El patrón es "YYYYMMddkm".

Are there any Joda time helper methods for this?

String 1: 2014041507393_somefile.somemore

String 2: _somefile2014041507393.somemore

preguntado el 28 de mayo de 14 a las 14:05

4 Respuestas

Utilice la siguiente expresión regular:

^\d{4}-\d{2}-\d{2}$

como en

String date = "2014041507393_somefile.somemore";

if (str.matches("\\d{4}-\\d{2}-\\d{2}")) {
    ...
}

contestado el 28 de mayo de 14 a las 14:05

javadoc says: Returns: true if, and only if, this string matches the given regular expression. Doesn't it mean that the WHOLE string needs to match the regex? - Lucas

As we are using a REGEX and not a single String, "string matches the given regular expression" means that the string matches with any of possible combination from regular expression - rafa romero

You will have to get rid of letters yourself. I don't think Joda time will have any methods to do this for you.

contestado el 28 de mayo de 14 a las 14:05

First use regular expression and then parse string in Java for use later:

if (str.matches("\\d{4}-\\d{2}-\\d{2}")) {
     Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(str);
    System.out.println(date); // Example: Sat May 14 00:00:00 BOT 2014
}

contestado el 28 de mayo de 14 a las 14:05

Use el parse método de SimpleDateFormat:

SimpleDateFormat format = SimpleDateFormat("YYYYMMddkm");
format.parse(string, pos);

contestado el 28 de mayo de 14 a las 14:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.