簡體   English   中英

在PostgreSQL中使用正則表達式從現有字符串創建新字符串

[英]Create new string from existing one using regex in Postgresql

我正在使用postgresql作為數據庫系統(v 9.6.5)。 我有一個帶有列code的表T。 我想添加一個新列sorting_code sorting_code是另一種編寫code

code是(按此順序)字符,數字和+的組合,例如12e+234rr++9999mo是代碼示例。 在正則表達式中,我的代碼是這樣的:

[0-9]+[az]*\\+* (僅數字)

我想對我的column sorting_code列進行的sorting_code就是像這樣轉換我的code

12e + => 000 12 0000 e 0000 +

234rr ++ => 00 234 000 rr 000 ++

9999mo => 0 9999 000 mo 00000

換句話說,每個部分(字符,數字和+)必須正好5個字符長。 缺少的字符將替換為0。

我的表T中已經有很多行帶代碼了。 創建新列sorting_code psql請求是什么?

謝謝

你可以做這樣的自行車:

t=# with s(v) as (values('12e+'),('234rr++'),('9999mo'))
, m as (select regexp_matches(v,'[a-z]{1,}','g') l,v,e,p , max(p) over(partition by v)
from s, regexp_split_to_table(v,'[a-z]') with ordinality o (e,p)
)
select lpad(m.e,5,'0')||lpad(m.l[1],5,'0')||lpad(n.e,5,'0') from m join m n on m.v = n.v and m.p=1 and n.p = n.max;
    ?column?
-----------------
 000120000e0000+
 00234000rr000++
 09999000mo00000
(3 rows)

我認為substring的正則表達式實現與lpad可以使您到達那里:

select
  val,
  lpad (coalesce (substring (val, '\d+'), ''), 5, '0') ||
  lpad (coalesce (substring (val, '[A-Za-z]+'), ''), 5, '0') ||
  lpad (coalesce (substring (val, '\++'), ''), 5, '0') as sorting_code
from t

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM