Reply to Re: Regex help

Your name:

Reply:


Posted by Michael Winter on 10/10/05 15:00

On 10/10/2005 11:23, BernieH wrote:

> I need a regex which will extract the year only from a variety of
> date strings such as -

Why a variety of formats? To ensure reliable results, it would be
necessary to first determine the format, then parse the string according
to what was detected. Obviously, the more formats you add, more code is
necessary (and subsequent testing) and the more chance of mismatches.
Unless you have a /real/ reason to be so flexible, enforce a small
number (preferably one) of distinct formats.

> April 8, 2000
> 13 May 1999
> April 1999
> 1999
> 20050908 (yyyymmdd format)
>
> The year will always be either the 1st 4 or the last 4 characters of
> the string.

In properly constructed strings, yes. However, are you parsing user
input or something generated mechanically? If it's the former, your
statement above cannot be regarded with /any/ confidence. If it's the
latter, you should be able to enforce just one format.

> What I have at the moment is ^([0-9]{4}).*$ for the YYYYMMDD format,
> but I'm not sure how to accomodate the first 3 examples. .*[0-9]{4}$
> doesn't seem to cut it.

You shouldn't be trying to match any character (that applies to both
expressions). Instead, you should be specific. The last format should
only be matched if there are eight consecutive digits.

/^(\d{4})\d{4}$/

The first four should be matched by zero or more non-digit characters,
followed by four digits that end the string.

/\D*(\d{4})$/

These could even be combined, but as I said at the beginning, I wouldn't
even use the second regular expression on its own, let alone combined
with another.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация