【问题标题】:PostgreSQL: Extract one word after a keyword from stringPostgreSQL:从字符串中提取关键字后的一个单词
【发布时间】:2020-10-28 17:50:58
【问题描述】:

我在 Postgres 中有一个如下所示的列,我只想拆分关键字旁边的字符。在下面的例子中,关键字是

“病人”

Patient Mark has tested positive
New update for Patient Wilson 
Discharged - Patient Thompson

我需要的结果列应该是这样的

Mark
Wilson
Thompson

【问题讨论】:

  • 您的样本值都不包含关键字product - 您的意思是Patient吗?
  • 关键字可能是“病人”
  • 对不起,是关键字耐心,我已经更新了

标签: postgresql substring string-matching


【解决方案1】:

假设您的数据在名为 str 的列中

尝试以下查询

SELECT 
  substring(split_part(str, 'Patient', 2) from '[^ ]+'::text) as patient_name 
FROM 
  table_name
;

【讨论】:

  • 执行查询时出现错误原因:SQL 错误 [XX000]:错误:未实现详细信息:---------- ------------------------- 错误:未实现代码:1001 上下文:'false' - 函数子字符串(文本,文本)未实现 - 使用 REGEXP_SUBSTR而是查询:75899630 位置:cg_expr_fn_builder.cpp:4510 进程:padbmaster [pid=31188]
  • 它的工作,检查这个小提琴,dbfiddle.uk/…
【解决方案2】:

您可以使用regexp_matches 函数。例如:

SELECT regexp_matches('Patient Mark has tested positive', 'Patient (\S+)');
 regexp_matches 
----------------
 {Mark}
(1 row)

SELECT regexp_matches('New update for Patient Wilson', 'Patient (\S+)');
 regexp_matches 
----------------
 {Wilson}
(1 row)

SELECT regexp_matches('Discharged - Patient Thompson', 'Patient (\S+)');
 regexp_matches 
----------------
 {Thompson}
(1 row)

在这种情况下,正则表达式 'Patient (\S+)' 返回关键字 Patient 之后直到下一个空格或字符串结尾的所有非空格字符

【讨论】:

    猜你喜欢
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2016-09-10
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    相关资源
    最近更新 更多