In this recipe, we will see how a small program may be written to take as input an amount string, and insert commas in it after every thousand (that is, every three digits from right). This is interesting because the normal search of a pattern within a text is from the left.
We will use the preview condition and the negated preview condition, along with subgroups in order to find a solution. Please note that one such example appears on the help.sap.com site under business warehouse routines that has been slightly modiied for this recipe.
For creating a program for comma insertion within an amount string, follow the following steps:
amount
of type character and length 10
. We can increase the length for a larger amount, keeping provision for the commas.REPLACE
statement with the addition ALL OCCURENCES
and REGEX '(d)(?=(d{3})+(?!d))'
and replace substring '$1,'
.write
statement is then used to output the convert amount.We have used subgroups in conjunction with the preview condition. The first subgroup denoted by (d)
is matched for digits within the number which subsequent numbers meet the condition specified by (d{3})+(?!d)
. (We may also write [0-9]
in place of d
).
The preview condition finds all numbers that are followed by one or more sequence of three digits after it starting from the left. (For this reason, the (d{3})+
has been used.) For example, we look for digits that are followed by three, six, or nine digits. (The negated preview condition ensures that only those numbers are matched, which have multiples of exactly three digit numbers after them.)
In case any such digit is matched, it is replaced using the register subgroup placeholder $1
followed by a comma. Suppose we choose 10000
as the input number, the first zero is the matched digit (and in this case) the only match. This is replaced by the zero itself followed by a comma. The match is shown in red in the following screenshot (output taken from DEMO_REGEX_TOY
program):
The output of the program is shown in the following screenshot:
If 100
is entered, the condition does not meet, so no matches are found. That is why no commas are inserted in the amount 100
at any position. Since a big amount may require more than one comma, we use the REPLACE ALL OCCURRENCES
addition.
3.135.190.182