[英]Check if a string has specific ending, erase this ending, then write those strings according to two other conditions
我必須從“sil.catalog_no”中提取字符串。
首先,我必須檢查一個字符串是否有'-UW'結尾並刪除它。
在那之后,我必須提取那個字符串(沒有-UW),但是在第一個' - '或第二個' - '之前沒有第一個部分,這取決於在第一個' - '之前是否有'US'。
我知道它搞砸了,但我不知道如何以其他方式描述它。
我已經嘗試了SUBSTRING,LEFT,RIGHT和CHARINDEX的東西,但是我的程序/數據庫/ sql版本(?)似乎沒有對這些東西進行操作,我找不到任何其他解決方案而不是這些。 也許是因為我沒有正確使用它們,我不知道。
sil.catalog_no中包含的字符串示例如下:
HU-98010587
US-HU-88136FYT-719-UW
所以,在第一個例子中,我只需檢查最后是否有'-UW'。 沒有一個,所以我轉到第二步,然后刪除'HU-'並提取其余的'98010587'。
對於第二個,我想檢查並從末尾刪除'-US'。 然后我想要抹掉整個'US-HU-',因為首先是'US'而我想獲得'88136FYT-719'。
編輯:
在重新思考問題后,我想我想知道擦除字符串特定部分的方法。 看一下我提供的圖像,我想刪除結果中出現的所有'HU-','EMC-','US-'和'-UW'。
好的,我認為regexp_replace
函數可以解決您的問題。 如下:
postgres=# select regexp_replace(regexp_replace('US-HU-88136FYT-719-UW','^([A-Z]+-)+',''),'(-[A-Z]+)+$','') as result;
result
--------------
88136FYT-719
(1 row)
postgres=# select regexp_replace(regexp_replace('HU-98010587','^([A-Z]+-)+',''),'(-[A-Z]+)+$','') as result;
result
----------
98010587
(1 row)
postgres=# select regexp_replace(regexp_replace('EMC-C13-PWR-7','^([A-Z]+-)+',''),'(-[A-Z]+)+$','') as result;
result
-----------
C13-PWR-7
或者我們更准確地刪除'HU-', 'EMC-', 'US-', '-UW'
,如下所示:
postgres=# select regexp_replace(regexp_replace('HU-98010587','^(HU-|EMC-|US-)+',''),'(-UW)+$','') as result;
result
----------
98010587
(1 row)
postgres=# select regexp_replace(regexp_replace('US-HU-88136FYT-719-UW','^(HU-|EMC-|US-)+',''),'(-UW)+$','') as result;
result
--------------
88136FYT-719
(1 row)
postgres=# select regexp_replace(regexp_replace('EMC-C13-PWR-7','^(HU-|EMC-|US-)+',''),'(-UW)+$','') as result;
result
-----------
C13-PWR-7
(1 row)
postgres=# select regexp_replace(regexp_replace('US-HU-88134UGQ-UW','^(HU-|EMC-|US-)+',''),'(-UW)+$','') as result;
result
----------
88134UGQ
我認為上面的兩個正則表達式可以得到正確的結果,第二個可以准確地滿足您的需求。 去嘗試一下。
另一種方法(在Postgres上嘗試過,但即使沒有正則表達式也可以使用,比如SQLite3):
drop table if exists t;
create table t(s varchar(30));
insert into t values
('HU-98010587'),
('US-HU-88136FYT-719-UW'),
('EMC-C13-PWR-7'),
('EMC-CTX-OM4-10M');
with xxx(original,s) as (
select s,substr(s,1,length(s)-3) from t where s like '%-UW'
union
select s,s from t where s not like '%-UW'
)
select original,substr(s,4) s from xxx where s like 'HU-%'
union
select original,substr(s,7) s from xxx where s like 'US-HU-%'
union
select original,s from xxx where s not like 'HU-%' and s not like 'US-HU-%';
為了得到您在編輯中所說的內容, I would like to erase all 'HU-', 'EMC-', 'US-', and '-UW' that appear in result
:
select s original,
replace(
replace(
replace(
replace(s,'HU-','')
,'US-','')
,'-UW','')
,'EMC-','') s
from t;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.