0

I have a string like 2005:10:29 12:23:53 and I wish to replace only first two occurrences of : with -

Expected result 2005-10-29 12:23:53

EDIT:

I need this regexp in KDE's krename tool, where I can't edit/format the original [exifExif.Image.DateTime] witch returns the unwanted 2005:10:29 12:23:53 format, but there is a Find and Replace to post process the String

(?<=\d{4}):|:(?=\d{2}\s) does the job on rubular, but does not in KDE :(

I am sure there are more solutions.

EDIT:

:(?=\d{2}:\d{2}\s)|:(?=\d{2}\s) works even on KDE

I find this solution after I read

You can use a full-fledged regular expression inside the lookahead.
Most regular expression engines only allow literal characters and
alternation inside lookbehind, since they cannot apply regular
expression backwards.

in Regex tutorial

kfl62
  • 2,434
  • 4
  • 29
  • 40

4 Answers4

3

In Ruby, as scibuff suggests, you're probably better not using Regexps.

require 'date'
date = DateTime.parse("2005:10:29 12:23:53", "%Y:%m:%d %H:%M:%S")
date.strftime("%Y-%m-%d %H:%M:%S")
Chowlett
  • 45,935
  • 20
  • 116
  • 150
1

JavaScript:

Version 1

str = str.split(' ')[0].replace(/\:/g,'-')+' '+str.split(' ')[1]

Version 2

str = str.replace(/(\d{4}):(\d{2}):(\d{2})(.*)/,"$1-$2-$3 $4")

DEMO

mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

Once again using regular expressions for something that can be achieved in a simpler, more elegant and more efficient way

var date = new Date('2005:10:29 12:23:53');

then format date accordingly, e.g.

function formatDate( date ){

    return date.getFullYear() + '-' + ( get.getMonth() + 1 ) + '-' + ... ;

}
scibuff
  • 13,377
  • 2
  • 27
  • 30
  • That would be wonderful if the Date function allowed yyyy:mm:dd hh:mm:ss - but it doesn't. So you need to first change the first set of : to - which is what OP wanted to know how to do – mplungjan Mar 22 '12 at 10:19
  • Sorry for confusing tags I removed them (javascript, ruby) – kfl62 Mar 22 '12 at 10:23
-1

Simply call replace() twice:

"2005:10:29 12:23:53".replace(/:/,'-').replace(/:/,'-')
codef0rmer
  • 10,284
  • 9
  • 53
  • 76