0

Hi I want to append a letter C to a string if it starts with a number . Also if it has any punctuation then replace with underscore _ Eg : 5-2-2-1 ==> C5_2_2_1

I tried ,but I am not able to replace the multiple occurrence of the punctuation. I am missing some simple thing, I cant get it.

SELECT  REGEXP_REPLACE('9-1-1','^(\d)(-),'C\1_' ) FROM DUAL;

2 Answers 2

2
SELECT case when REGEXP_LIKE('9-1-1','^[[:digit:]]') then 'C' END 
       || REGEXP_REPLACE('9-1-1', '[[:punct:]]', '_')
FROM DUAL;

[:digit:] any digit
[:punct:] punctuation symbol

if you have a lot of rows with different values then try to avoid regex:

SELECT case when substr('9-1-1',1,1) between '0' and '9' then 'C' end
       || translate('9-1-1', ',.!-', '_')
FROM DUAL;

Check here for example: Performance of regexp_replace vs translate in Oracle?

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

3 Comments

Thanks a lot it works! I was just trying to minimize multiple functions because I'll be scanning this through millions of rows
@Raj A I've added some more info. I didn't know about millions of rows
Thanks so much for your effort and the link!!
1

Try this:

select (case when substr(val, 1, 1) between '0' and '9' then 'C' else '' end) ||
       regexp_replace(val, '([-+.,;:'"!])', '_')

3 Comments

Thanks a lot for the quick reply !!,Just out of curiosity if there a way to do it in once regular expression function
@RajA . . . I don't think there is a way to do this with one function.
..Hmmm I was thinking if anyhow we can capture more than one occurance of a character..But its okay, I will use this..Thanks again

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.