开发者

How can you capture this with regex?

I am trying to capture a conditional of years in RegEx. Basically, if they implement ju开发者_运维技巧st a two digit year, I want to make it a four digit year. So if they put :

1/2/08

I want to make it :

1/2/2008

Any ideas?


One [pretty nasty] way using regex:

"1/2/08".sub! /\/(\d{2})$/, '/20\1'

Wouldn't it be better to just parse the string into a date object, though? Then you can treat it as a date properly! :)


You could split on '/' and if the last component has a length of two you prepend 20 and then assemble the date again.


You could split the string up using

(.*/)(..)$

and then substitute with something like

$120$2

to put the string back together (tested with http://www.regexplanet.com/simple/).

You might need to think about what you want to happen for dates in the 20th century - this approach will recognise 21/01/98 as 21/01/2098 which might not be what you want... It might be better to parse the string out properly rather than just blindly regex it!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜