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:
mydate
having a length of 10
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.replace
statement having the regex '(d{4})(d{2})(d{2})'
is used, along with the replacement '$3/$2/$1'
.We have used three subgroups in the formation of the regular expression. The d
refers to digits and the number given in curly brackets specifies the length of the various date components (4
for year, 2
for month and the date). The three subgroups are specified using parentheses.
Within the replace
statement, the subgroup placeholders are used. It specifies the format in which the date is to be outputted (the year followed by a forward slash, then the month, then another forward slash, and finally the date). For the input date, 20120101
, following are the values in each of the subgroup registers:
$1
: 2012
$2
: 01
$3
: 01
In this case, the date after the replace
statement and the write
statement is shown in the following screenshot:
3.144.123.155