3

I have this expression in the field calculator:

regexp_replace('1', '^(\\d+)', rpad('\\1', 3, '0') ) gives 01 rather than 001 as expected.

the *pad functions work fine when called outside regexp_replace

Weird! This has to be a bug? or am I missing something?

If it is a bug I'll log something in the issue tracker.

BTW I was delighted when I found I could use complex expressions including functions in the third parameter of regexp_replace! kudos to the QGIS developers!

  • What does rpad('22',3,'0') give you? – Nathan W Jan 19 '14 at 11:07
  • '022' as expected. The problem appears when the *pad function is called in regexp_replace. I'll edit the main question to insert an image from the calculator that uses static strings. – Russell Fulton Jan 19 '14 at 23:22
  • I ended up radically simplifying the question to use a static example. – Russell Fulton Jan 19 '14 at 23:39
  • Shouldn't it be lpad rather than rpad? – AndreJ Sep 18 '16 at 5:45
0

It's not a bug in any of the functions, more an implementation detail that isn't evident at first look.

The expression engine evaluates from inside out, so rpad is run first with no concept of the outer function or the regex.

This is run first:

rpad('\\1', 3, '0')

which it looks at and goes "Ok cool I can pad that for you". The result:

\10

the \\ will escape the \ so you end up with it in your final output. Three characters just like you asked for, well as far as the expression is concerned.

By the time your regexp_replace runs it looks like this:

regexp_replace('3', '^(\\d+)', '\10' )

and at that point regexp_replace is doing what it is told. Replacing the first group with replace string. So you end up with 30.

  • I was very surprised when this appeared to work at all. I am guessing I need to do this in a script of some sort. – Russell Fulton Jan 20 '14 at 6:22
  • or just increase the pad number by 1 :) – Nathan W Jan 20 '14 at 6:29
  • I did that before I posted the question ;) – Russell Fulton Jan 21 '14 at 1:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.