tags:

views:

46

answers:

5

Hi , can someone help me what would be the regular expression in java for the string "Feb. 26, 2009 8:08 AM PST"????

+4  A: 

Use SimpleDateFormat instead of using regexp. Read the tutorial for more info.

UPD: regexp will look like: "(Jan|Feb|Mar).*PST" where list of months should contain all 12 (instead of 3 as in my example). But it's very very unreliable.

Roman
Joda Time is better still.
Freiheit
@Freiheit: everytime I see a question about dates in java I'm waiting for the answer/comment like "and don't forget that java dates are broken, use Joda Time instead". And as I understand I'm not alone in this habit.
Roman
A: 

SimpleDateFormat with parse would probably be simpler in Java. See example below. The Javadoc shows what each of the letters in the pattern means.

DateFormat formatter = new SimpleDateFormat("MMM. dd, YYYY h:mm a Z");
Date date = null;
try {
   date = formatter.parse(datestring);
} catch(ParseException pe) {
   throw new IllegalArguementException(datestring + " is not properly formatted!", pe);
}
justkt
A: 

ya but the problem is that the date which i am trying to extract is nested inside some text. So i was looking for a regex and using it with split method of string in java to extract the dates from the particular string.

sahmed
Is it an arbitrary date? An arbitrary timezone? The more you can guarantee about the date, the simpler the regex will be.
justkt
A: 

Its actually a simple date with just the above format. I just need to match dates out from a huge text document, and extract them out.

str.split("regex for the above date");

sahmed
Update your question instead of posting updates in answers.
Roman
@sahmed - it will be a little bit (in reputation) before you can post comments everywhere, but you should be able to update your own question and also comment on it - check it out and see!
justkt
A: 

i think my approach is wrong. If i use str.split("regex for date"); to extract all the dates from the text. Its not gonna do that but it will retain the other text and split the document when the date occurs.

How do i do what i intend to do , that is from a text extract all the dates perferably in an array which corresopnds to the above format of date??

sahmed
Look at `Pattern` and `Matcher` in the Java API. Those will do what you want. Also, consider using comments and editing your original post. This would be an ideal edit.
justkt