As already mentioned, regular expressions are useful for converting data into the required format. One good example is the conversion of a date stored in internal format into display format, and vice versa. For example, a date may be available as 20120101
and we need to format it in the form 01/01/2012
, and so on. In this recipe, we will see how a single statement of replace
may be used to carry out this task. For this recipe, we assum that input date is in the correct internal format.
For carrying out the previously mentioned conversion, proceed as follows:
First, declare a variable
mydate
having a length of10
characters. A date having the internal format date is then assigned to this variable. The same variable will be used for storing the converted date.The
replace
statement having theregex '(\d{4})(\d{2})(\d{2})'
is used, along with the replacement'$3/$2/$1'
.The converted date is then outputted on the screen.