Search code examples
vbscriptqtphp-uft

How to add zero to single digit in a string


I need to to append zero in my below string whenever I get date with single digit without changing Quantity digit (below string is system generated in my application not created by user),

Data Added Quantity:1 on Dec 9 2015 modified on Jun 7 2016

I need to change this string just like below,

Data Added Quantity:125 on Dec 09 2015 modified on Jun 07 2016

So far I have tried the below regular expression, but not getting desired output.

str = "Data Added Quantity:1 on Dec 9 2015 modified on Jun 7 2016"
Set oReg = New RegExp
oReg.Pattern = "\s\d{1}\s"
Set obj = oReg.Execute(str)
For i = 0 To obj.Count-1
  mD = obj.Item(i).Value
  oReg.Replace(str, "0" & mD)
Next

How we can achieve this using VBScript?


Solution

  • If you adjust the pattern a little and set the Global option to True you can simply use the Replace method. No need to Excecute and loop.

    Set re = New RegExp
    re.Pattern = "\s(\d)\s"
    re.Global  = True
    
    str = re.Replace(str, " 0$1 ")
    

    \d without a modifier already matches exactly one digit, so \d{1} is redundant. The parentheses around the \d define a capturing group that allows you to use the matched substring in the replacement ($1).