【问题标题】:REGEXP_LIKE in PostgresqlPostgresql 中的 REGEXP_LIKE
【发布时间】:2019-11-28 01:30:06
【问题描述】:

我有一个表来存储替换,其中包括两个字段,第一个是存储单词,第二个是存储替换。我知道创建表不是一种合适的方法,但它已经到位并被其他系统使用。

表格如下所示:

WORD        SUBS_LIST
------------------------------------
MOUNTAIN    MOUNTAIN, MOUNT, MT, MTN
VIEW        VIEW, VU
FIFTH       V, 5TH
YOU         EWE, U , YEW
ROW         ROW , ROE
ONE         UN , ONE

然后,当一个名字进来时,它是根据表格替换的。我能够使用 regexp_like 在 Oracle 上进行先前的操作。但是,我想在 Postgresql 中应用相同的方法。我尝试使用 ~ 替换 regexp_like 和 regexp_matches 但没有成功。

请找到here 到目前为止我尝试过的 DBFiddle。

感谢您的帮助:)

【问题讨论】:

  • 最好将您的尝试从小提琴中包含到您的问题中,以便更清楚您想要实现的目标。

标签: regex postgresql sql-like regexp-like


【解决方案1】:

你不需要正则表达式。如果我理解正确,您想输入一个单词,搜索 sub_list 中的元素并返回 word 列。最好将(丑陋的)逗号分隔列表转换为数组,然后使用 ANY 运算符:

select word
from the_table
where 'mount' = any(string_to_array(subs_list, ','));

上面将正确处理您在, 周围的空白 - 不确定这是您格式化的结果还是您真的以这种方式存储列表。如果确实需要处理空格,可以使用以下方法:

select word
from the_table
where exists (select *
              from unnest(string_to_array(subs_list, ',')) as x(subs)  
              where trim(x.subs) = 'mount');

如果您的输入是单词列表,您可以使用regexp_split_to_table() 将输入的单词转换为行并加入替换。

SELECT w.input, coalesce(x.word, w.input) as word
FROM regexp_split_to_table('MOUNT VU FOOD CAFE', '\s') as w(input) 
  LEFT JOIN (
    select s.word, trim(s1.token) as token
    from subs s
      cross join unnest(string_to_array(s.subs_list, ',')) s1(token)
  ) as x on lower(trim(w.input)) = lower(x.token)
;

在线示例:https://rextester.com/DZBF77100

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多