Get Month from Date in Log File

sbowde4 :

I have an input String formatted like this.

96.7.4.14 - - [24/Apr/2011:04:20:11 -0400] "GET /cat.jpg HTTP/1.1" 200 1243

I know how to get the entire date from the string, but what would be the best way to just extract the three letter month code?

Yassin Hajaj :

You can use the following regex to extract the three letters month

(?<=\d{2}\/)(\w{3})(?=\/\d{4})

What it does basically is lookbehind to find two digits and a slash and also lookahead to find a slash and 4 digits while matching three word characters.


Alternative, an even simpler solution, without using regular expressions, given the beginning of the string always contains the same formatted characters is the following

String text = "96.7.4.14 - - [24/Apr/2011:04:20:11 -0400] \"GET /cat.jpg HTTP/1.1\" 200 1243";
int firstLetterOfMonth = text.indexOf('/') + 1;
String month = text.substring(firstLetterOfMonth, firstLetterOfMonth + 3);
System.out.println(month); // Apr

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147531&siteId=1