簡體   English   中英

從PostgreSQL中的文本字段中提取字符串(使用正則表達式?)

[英]Extract string from text field in PostgreSQL (using regex?)

我有很多有citydirection字段的行。 但是從舊的進口來看,城市和方向在direction領域是混合的。 喜歡:

dir number,  extra data, CITY,  AL 111111
dir number, CITY,  AL 111111
number, dir, number, CITY, dir number, CITY,  AL 111111

重要的是'CITY'總是出現在美國郵政編碼之前,我想提取它並將其保存在city領域並使用UPDATE (使用正則表達式?)。 可能嗎?

就像是:

update TABLE set city = SOME_REGEX_MAGIC_FROM_DIRECTION_FIELD
where direccion ~ 'REGEX_MAGIC'

工作的SQL語句:

update TABLE
set city = substring(direction FROM '([^,]+),[^,]+$')
where direction like '%,  __ _____';

如果你想要在最后一個逗號之前的部分,一種方式(很多)是使用普通的substring()調用(regexp變體):

substring(direction FROM ',([^,]+),[^,]+$') AS city

db <>在這里小提琴

您的UPDATE語句可能如下所示:

UPDATE tbl
SET    city = substring(direction FROM ',([^,]+),[^,]+$')
WHERE  direction ~ ', *\D\D \d{5}$'

從你的數據我會得到你需要這樣的東西:

SELECT regexp_matches('direction_field', '([^,]+) \d{5}');

從Redshift中的正則表達式獲取子字符串:

SELECT REGEXP_SUBSTR(
   'hello_uuid_092bab12-8d8b-40ad-b8b7-bc9f05e52c9c_something_else',
   '([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})'
)

結果: 092bab12-8d8b-40ad-b8b7-bc9f05e52c9c

暫無
暫無

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

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