Scala regex find/replace with additional formatting -
i'm trying replace parts of string contains should dates, possibly in impermissible format. specifically, of dates in form "mm/dd/yyyy" , need in form "yyyy-mm-dd". 1 caveat original dates may not exactly in mm/dd/yyyy format; "5/6/2015". example, if
val x = "where date >= '05/06/2017'"
then
x.replaceall("'([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})'", "'$3-$1-$2'")
performs desired replacement (returns "2017-05-06"), for
val y = "where date >= '5/6/2017'"
this not return desired replacement (returns "2017-5-6" -- me, invalid representation). joda time wrapper nscala-time
, i've tried capturing dates , reformatting them:
import com.github.nscala_time.time.imports._ import org.joda.time.datetime val f = datetimeformat.forpattern("yyyy-mm-dd") y.replaceall("'([0-9]{1,2}/[0-9]{1,2}/[0-9]{4})'", "'"+f.print(datetimeformat.forpattern("mm/dd/yyyy").parsedatetime("$1"))+"'")
but fails java.lang.illegalargumentexception: invalid format: "$1"
. i've tried using f
interpolator , padding 0s, doesn't seem either.
are not able additional processing on captured groups ($1
, etc.) inside replaceall
? if not, how else can achieve desired result?
the $1
backreferences can used inside string replacement patterns. in code, "$1"
not backreference longer.
you may use "callback" replaceallin
match object , access groups further manipulate them:
val pattern = "'([0-9]{1,2}/[0-9]{1,2}/[0-9]{4})'".r y = pattern replaceallin (y, m => "'"+f.print(datetimeformat.forpattern("mm/dd/yyyy").parsedatetime(m.group(1)))+"'")
Comments
Post a Comment