insert a character within a string [message #622703] |
Thu, 28 August 2014 11:18 |
deahayes3
Messages: 203 Registered: May 2006
|
Senior Member |
|
|
Hello all,
I need help creating a query that will insert a colon from the third position counting from the end of the string.
for example '1135' replace with '11:35',what function(s) should I use?
Thanks.
|
|
|
|
|
|
|
|
|
|
|
Re: insert a character within a string [message #622714 is a reply to message #622703] |
Thu, 28 August 2014 12:22 |
Solomon Yakobson
Messages: 3273 Registered: January 2010 Location: Connecticut, USA
|
Senior Member |
|
|
deahayes3 wrote on Thu, 28 August 2014 12:18insert a colon from the third position counting from the end of the string.
SELECT REGEXP_REPLACE('&str','(..$)',':\1') X
FROM DUAL
/
Enter value for str: 1135
old 1: SELECT REGEXP_REPLACE('&str','(..$)',':\1') X
new 1: SELECT REGEXP_REPLACE('1135','(..$)',':\1') X
X
-----
11:35
SQL> /
Enter value for str: 345
old 1: SELECT REGEXP_REPLACE('&str','(..$)',':\1') X
new 1: SELECT REGEXP_REPLACE('345','(..$)',':\1') X
X
----
3:45
SQL> /
Enter value for str: 12345
old 1: SELECT REGEXP_REPLACE('&str','(..$)',':\1') X
new 1: SELECT REGEXP_REPLACE('12345','(..$)',':\1') X
X
------
123:45
SQL> /
Enter value for str: 12
old 1: SELECT REGEXP_REPLACE('&str','(..$)',':\1') X
new 1: SELECT REGEXP_REPLACE('12','(..$)',':\1') X
X
---
:12
SQL> /
Enter value for str: 1
old 1: SELECT REGEXP_REPLACE('&str','(..$)',':\1') X
new 1: SELECT REGEXP_REPLACE('1','(..$)',':\1') X
X
-
1
SQL>
SY.
|
|
|
|
|
|
Re: insert a character within a string [message #622755 is a reply to message #622730] |
Fri, 29 August 2014 02:53 |
cookiemonster
Messages: 13920 Registered: September 2008 Location: Rainy Manchester
|
Senior Member |
|
|
The non regexp solution also requires length(and decode if you can have 1 digit numbers):
SQL> WITH DATA AS (SELECT 12345 a FROM dual
2 UNION ALL
3 SELECT 1234 a FROM dual
4 UNION ALL
5 SELECT 123 a FROM dual
6 UNION ALL
7 SELECT 12 a FROM dual
8 UNION ALL
9 SELECT 1 a FROM dual)
10 SELECT a, SUBSTR(a, 1, LENGTH(a) - 2)||':'||SUBSTR(a,DECODE(LENGTH(a),1,-1,-2))
11 FROM DATA;
A SUBSTR(A,1,LENGTH(A)-2)||':'||
---------- --------------------------------------------------------------------------------
12345 123:45
1234 12:34
123 1:23
12 :12
1 :1
|
|
|