From: Tom Anderson on
On Mon, 28 Jun 2010, Arne Vajh?j wrote:

> On 28-06-2010 11:30, Tom Anderson wrote:
>> On Mon, 28 Jun 2010, student4life wrote:
>>> Could someone show me the best way to parse the first occurrence of
>>> dates (could be in different date formats, MM/dd/yy, yyyy/MM/dd, etc.)
>>> in a string preferably without using regular expression?
>>
>> A regular expression is far and away the best way of doing this. Why
>> don't you want to use one?
>
> If the position of the date is unknown, then regex is a very good
> choice for finding candidates.
>
> DateFormat.parse should still be used to verify, because regex
> is not the right tool to discard February 30th etc..

I strongly agree with this.

I suppose a way you could do it without a regexp would be:

public Date findDateInString(String s) {
for (int i = 0; i < s.length(); ++i) {
Date d = DATE_FORMAT.parse(s.substring(i));
if (d != null) return d;
}
throw new IllegalArgumentException("no date found in string: " + s);
}

Anyone who does that needs a beating, though.

tom

--
Fitter, Happier, More Productive.
From: Lew on
student4life wrote:
>>>> Could someone show me the best way to parse the first occurrence of
>>>> dates (could be in different date formats, MM/dd/yy, yyyy/MM/dd, etc.)
>>>> in a string preferably without using regular expression?
>

Tom Anderson wrote:
>>> A regular expression is far and away the best way of doing this. Why
>>> don't you want to use one?
>

Arne Vajhøj wrote:
>> If the position of the date is unknown, then regex is a very good
>> choice for finding candidates.
>>
>> DateFormat.parse should still be used to verify, because regex
>> is not the right tool to discard February 30th etc..
>

Tom Anderson wrote:
> I strongly agree with this.
>
> I suppose a way you could do it without a regexp would be:
>
> public Date findDateInString(String s) {
>         for (int i = 0; i < s.length(); ++i) {
>                 Date d = DATE_FORMAT.parse(s.substring(i));
>                 if (d != null) return d;
>         }
>         throw new IllegalArgumentException("no date found in string: " + s);
>
> }
>
> Anyone who does that needs a beating, though.
>

To really earn that beating, use the ParsePosition forms of 'parse()'
in that loop:
<http://java.sun.com/javase/6/docs/api/java/text/
DateFormat.html#parse(java.lang.String, java.text.ParsePosition)>
et seq.

We still need to hear from the OP why they wish to avoid regexes.

--
Lew