2

I'm trying to write a postgres function that will sanitize a list of numbers into a list of comma-separated numbers. These numbers are being entered into an input field. I want to allow users to just enter a line of space-separated numbers (ex: 1 3 4 12) and have it change it to 1,3,4,12.

But, if they do enter it correctly (ex: 1,3,4,12 or 1, 3, 4, 12), I still want it to sanitize it to 1,3,4,12. I also have to account for things like (ex: 1, 3 4, 12).

This is what I'm currently doing:

select regexp_replace(trim(list_of_numbers), '[^0-9.] | [^,]', ',', 'g')

If I have a list like this:

select regexp_replace(trim('1, 2, 4, 14'), '[^0-9.] | [^,]', ',', 'g')

it returns : "1,2,4,14" so that's good.

But, if I have a list like this:

select regexp_replace(trim('1 2 4 14'), '[^0-9.] | [^,]', ',', 'g')

it returns : "1,,,4"

0

3 Answers 3

1

If you change your regex to [^0-9.]+ it'll replace all non-numerics (i.e. , ,, ,) with a ,.

Try it out here

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

Comments

0

I think the best option is to convert to an array using regexp_split_to_array then turn that back into a string:

The following:

with t(input) as (
  values 
    ('1 3 4 12'), 
    ('1,3,4,12'),
    ('1, 3 4, 12'),
    ('1,3,4,12'),
    ('1   3  4 , 12'),
    ('   1,  2  , 4 12   ')
)
select array_to_string(regexp_split_to_array(trim(input),'(\s+)|(\s*,\s*)'), ',')
from t;

returns:

array_to_string
---------------
1,3,4,12       
1,3,4,12       
1,3,4,12       
1,3,4,12       
1,3,4,12       
1,3,4,12       

2 Comments

Your regex would match many spaces multiple times, f.e. "1____4" becomes "1,,,4". I thought (,|\s)+ for any combination of whitespace is a better fit
This works unless the user enters extra spaces (ex: '1, 2, 4 12'). Then you get "1,2,4,,,,12".
0

You could split the string on any amount of whitespace or commas (,|\s)+ and join it back together using commas:

select array_to_string(regexp_split_to_array('1 2 4 14', '(,|\s)+'), ', ');

3 Comments

The issue with this is that you'll get redundant commas, e.g. 1, 2 3 4 -> 1,,2,3,4
That works if they enter it like, '1 2 3 14', but if they actually put in commas like, '1, 2, 3, 14', it adds extra commas (""1,, 2,, 4,, 14"").
Added commas as part of the split regex, should work now

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.