0

I have a string which has at least one digit per bracket. Now, I want to extract the digit(s). How do I do this in Redshift sql?

    ColumnA     ColumnB (output)
    (,,,3,)     3
    (2,,,)      2
    (,,,1)      1
    (1,,,3)     13
8
  • regex (\d+) will work. Commented Sep 6, 2022 at 22:20
  • For that 4th example, what's the intended value to extract? You've got two digits in the bracket. Commented Sep 6, 2022 at 22:21
  • @JakobLovern just added that use case. Commented Sep 6, 2022 at 22:22
  • 1
    @titutubs you say one digit per bracket, but your last row has two digits. Commented Sep 6, 2022 at 22:26
  • 1
    If you search and replace on [^\d]=>(empty) then it'll delete everything that's not a digit. See regex101.com/r/zIRBtS/1 Commented Sep 6, 2022 at 22:28

2 Answers 2

2

You could use REGEXP_REPLACE. Here's a snippet:

CREATE TABLE x (col1 varchar(255))

INSERT INTO x VALUES ('(,,,3,)'),('(2,,,)'),('(,,,1)'),('(1,,,3)');
select col1, 
       regexp_replace(col1,'[^\d]','','g') as col2
from x;

col1 col2
(,,,3,) 3
(2,,,) 2
(,,,1) 1
(1,,,3) 13

Try it in SQLFiddle

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

2 Comments

@Jajob Lovern what is the 'g' for? I am getting an error
The 'g' is a regex flag indicating to replace all matches.
2

Jakob's answer would work. You can also do the same thing with REPLACE:

CREATE TABLE x (col1 varchar(255)) 
INSERT INTO x VALUES ('(,,,3,)'),('(2,,,)'),('(,,,1)'),('(1,,,3)')

SELECT REPLACE(
    REPLACE(
        REPLACE(
          col1, ',', ''
        ) ,')', ''
    ), '(', ''
) FROM x
replace
3
2
1
13

SQLFiddle

1 Comment

This answer is probably more portable tbh. I've had spotty reception with REGEXP_REPLACE across databases, while REPLACE is part of the ansi spec.

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.