I need to be able to look for a number followed by a colon, add a zero to any single digit number, retain the original number, and leave the colon in place plus all text that follows.
I am working in Google Sheets
Example:
1: Assignment One ➡ 01: Assignment One
if the number is double or triple digit (i.e. 10: Assignment Ten or 100: Assignment 100) then it does not add a leading zero.
What I have tried
I have looked all over for a simple regex solution and nothing I have found works for me in Google Sheets.
I had to resort to a Google Sheet formula to produce the result I wanted. I have a list of assignments that our system lists as:
1: Assignment One
2: Assignment Two
…
10: Assignment Ten
11: Assignment Eleven
…
20: Assignment Ten
21: Assignment Eleven
…
Etcetera. I tried to get a RegEXReplace to change those to:
01: Assignment One
02: Assignment Two
Because as is, when I try to sort by assignments, I get
1: Assignment One
10: Assignment Ten
11: Assignment Eleven
…
2: Assignment Two
20: Assignment Twenty
…
Because string sorts work that way…
Non-Regular Expresseion fix
After days of stubbornly trying to find a RegEx solution, I went to a simple Formula:
=arrayformula(if(J3:J=””,””,if(right(left(J3:J,2),1)=”:”,”0″&J3:J,J3:J)))
Looks at J3:J cells, picks up the two left-most characters, picks out the last of those characters to see if it is a colon (:). If it is a colon, it is a number from 1-9 and needs to be changed by adding a leading zero. If it is not a column, then it is a number <=10 and does not need to be changed. It was a simple 15 second solution, but one that I did not want to use because I am tryng to understand/learn/use regular expressions…
It irks me that I could not figure out how to do that with a regex expression. I can FIND the numbers needing to be changed rather easily with
RegExReplace(J3:J,”^[0-9]:”,”But I cannot figure out the replacement that leaves the number and just adds a zero in front of it”)
Can anybody help?
Bernabe Garcia is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.