So I have been trying to take off a timestamp from a string, a file name to be more specific.
I tried making a substring, but the size of the timestamp is variable.
For example, sometimes it's like this:
2016-05-05 03:45:00.907text.txt
and sometimes like this:
2016-05-05 03:45:00.83text.txt
Maybe regex is the answer?
The string to be processed will always have a timestamp plus a filename. The filename can start with numbers or letters.
I forgot to say it's for Java.
String input = "2016-05-05 03:45:00.907text.txt";
String regex = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d+";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if(matcher.find()){
String output = matcher.group();
Date date = formatter.parse(output);
long time = date.getTime();
System.out.println(time);
}
You have to find the date with regex, then you convert the String in a proper Date and then you can get the timestamp.
this sed will cleanup the timestamp
$ echo "2016-05-05 03:45:00.83text.txt" |
sed -r 's/^[0-9]{4}(-[0-9]{2}){2} ([0-9]{2}:){2}[0-9]{2}\.[0-9]{2,3}//'
text.txt
will also work for the other case, however it will not know the difference if your file name is "7text.txt".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With