Adding a decimal separator and two zeros after a single digit integer number in text

Data:

x <- c("3%-1ST $100000 AND 1.25% BALANCE", 
       "3.22%-1ST $100000 AND 1.25% BALANCE", 
       "12.15% AND 5%")

Solution:

gsub("(?<!\\d\\.\\d)(\\d)(%)", "\\1.00\\2", x, perl = T)
[1] "3.00%-1ST $100000 AND 1.25% BALANCE" "3.22%-1ST $100000 AND 1.25% BALANCE" "12.15% AND 5.00%" 

The solution lies not in using word boundaries but defining a negative condition on which the substitution is not to take place. That negative condition is implemented using negative lookbehind (?<!...).

The lookbehind in more detail:

  • (?<!: this initializes negative lookbehind, which is an instruction to match if to the left you do not see …

    • \\d: a digit
    • \\.: a period
    • \\d: a digit
  • ): this bracket concludes the negative lookbehind

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top