2015-12-04 68 views
0

說我有一個像IPv6地址:正則表達式來格式化IPv6地址 - 刪除前導零

2001:04E8:0000:4001:0000:0000:0000:0000/64 

而且我想輸出像

2001:4E8:0:4001:0:0:0:0/64 

因此,基本上,它消除前導零,並在同一時間,用一個零代替四個零。

replaceAll("(:(0)*)|(^0+)",":") 

上述正則表達式做工作,但給人的

2001:4E8::4001::::/64 

都省略了四個零輸出。

注:輸入可以是任何有效的IPv6地址

+0

哪個DBMS您使用的?替換/正則表達式功能在產品之間往往有點不同。 – jarlh

+0

oracle數據庫 – user1933888

回答

0

在java中,像這樣的工作:

replaceAll("(:000)|(:0*)", ":"); 
1

您可以使用REPLACE兩次,SUBSTR刪除前導0

SELECT ipv6, 
     SUBSTR(REPLACE(REPLACE(':' || ipv6, ':00', ':'),':0', ':'),2) AS result 
FROM tab; 

SqlFiddleDemo

演示使用MySQL,因爲Oracle沒有響應。唯一的變化是字符串連接。

輸出:

╔═════════════════════════════════════════════╦════════════════════════════╗ 
║     ipv6      ║   result   ║ 
╠═════════════════════════════════════════════╬════════════════════════════╣ 
║ 2001:04E8:0000:4001:0000:0000:0000:0000/64 ║ 2001:4E8:0:4001:0:0:0:0/64 ║ 
║ 0000:0001:0012:0123:1234:0000:0000:0000/64 ║ 0:1:12:123:1234:0:0:0/64 ║ 
║ 0001:04E8:0000:4001:0000:0000:0000:0000/64 ║ 1:4E8:0:4001:0:0:0:0/64 ║ 
║ 0012:04E8:0000:4001:0000:0000:0000:0000/64 ║ 12:4E8:0:4001:0:0:0:0/64 ║ 
║ 0123:04E8:0000:4001:0000:0000:0000:0000/64 ║ 123:4E8:0:4001:0:0:0:0/64 ║ 
╚═════════════════════════════════════════════╩════════════════════════════╝ 
1

樣品使用Oracle的REGEXP_REPLACE:

SQL> with t as (
    2 select '2001:04E8:0000:4001:0000:0000:0000:0000/64' str from dual union all 
    3 select '0000:0001:0012:0123:1234:0000:0000:0000/64' from dual union all 
    4 select '0001:04E8:0000:4001:0000:0000:0000:0000/64' from dual union all 
    5 select '0000:0001:0012:0123:1234:0000:0000:0000/64' from dual 
    6 ) -- end of sample data 
    7 select regexp_replace(str, '(:|^)(0{0,3})([1-9]*)', '\1\3') str 
    8 from t; 
STR 
-------------------------------------------------------------------------------- 
2001:4E8:0:4001:0:0:0:0/64 
0:1:12:123:1234:0:0:0/64 
1:4E8:0:4001:0:0:0:0/64 
0:1:12:123:1234:0:0:0/64 
+0

我喜歡這個解決方案,當輸入像'2001:04E8:0000:4001:0000:0:0000:0/64'時,我看到的只有問題是 ' 輸出將是'2001:04E8:0000:4001 :0 :: 0:/ 64' – user1933888