I have a series of strings in my table that I want to order. eg.
Chapter 1
Chapter 2
Chapter 11
Chapter 12
To order them correctly I would need to pad them with zeros.
Chapter 001
Chapter 002
Chapter 011
Chapter 012
Maybe I can use regexp_replace()
pad in zeros with the use of a regular expression.
regexp_replace(chapters.name,'(\d+)\D*','0\1') as name
This solution does not work. I thought maybe I could figure out the length of the backreference and use that number to pad what I need:
regexp_replace(chapters.name,'(\d+)\D*',lpad('\l',3-length('\1'),'0') as name
but a \1
in length()
always returns 2, even though I noticed using \1
in certain postgres function translate \1
to the actual captured data.
How can I pad zeros using Postgres string functions and Postgres regex?