2

I need to remove '.0' at the end of the string but I have some issues.

In PG 8.4 I have this expression and its was worked fine.

select regexp_replace('10.1.2.3.0', '(\\\\.0)+$', '');

and result was

'10.1.2.3' - good result.

But after PG was updated to 9.x version result is

'10.1.2.3.0' - the input string and its not ok.

Also I tried to use trim function

it this case it is ok

select trim('.0' from '10.1.2.3.0');

result is '10.1.2.3' - ok

but when I have 10 at the end of the code I have unexpected result

select trim('.0' from '10.1.2.3.10.0');

or

select trim('.0' from '10.1.2.3.10');

result is 10.1.2.3.1 - 0 is trimmed from 10

Somebody can suggest me solution and explain what is wrong with trim function and what was changed in regexp_replace in latest versions?

1
  • Not seen anything stating why this does what it does - trim removes the longest string containing ANY of the matching characters from the start and end of the string, so '.0' removes any '0' or '.' characters at the end of the string, so from '10.0' it removes both zeros and the period, leaving just '1' behind. Commented Jun 20 at 12:18

1 Answer 1

3

I would suggest doing something like this:

select (case when col like '%.0' then left(col, length(col) - 2)
             else col
        end)

This will work in all versions of Postgres and you don't need to worry about regular expression parsing.

As for the regular expression version, both of these work for me (on recent versions of Postgres):

select regexp_replace('10.1.2.3.0', '(\.0)+$', '');
select regexp_replace('10.1.2.3.0', '([.]0)+$', '');

I suspect the problem with the earlier version is the string parsing with the backslash escape character -- you can use square brackets instead of backslash and the pattern should work in any version.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! :) Yes problem is with backslash escape character and its behavior was changed across versions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.