【问题标题】:Regular expression to find one of two strings when one consists the other正则表达式在一个包含另一个字符串时查找两个字符串之一
【发布时间】:2019-06-22 04:18:03
【问题描述】:

在 PostgreSQL 中使用。 我有一组字符串,例如:

xxx Heartbeat
yyy Heartbeat
xxx Code Red Entry/Exit
yyy Code Red Entry/Exit
xxx TFTP Server Heartbeat
yyy TFTP Server Heartbeat

我需要拆分第二部分,它位于未知字符串 xxx/yyy 之后,其中可以有空格。在我有不交叉的搜索字符串并使用以下排序之前:

SUBSTRING(description, '(?i).*(Code Red Entry/Exit|TFTP Server Heartbeat).?')

但是在我有了另一个(心跳)选项之后,如果我使用,这个正则表达式开始在所有情况下都只选择“心跳”

SUBSTRING(description, '(?i).*(Code Red Entry/Exit|TFTP Server Heartbeat|Heartbeat).?')

我该如何解决?

更新。 基本上我需要一个正则表达式替代下一个代码:

CASE WHEN description ILIKE '%TFTP Server Heartbeat' THEN 'TFTP Server Heartbeat' 
     WHEN description ILIKE '%Heartbeat' THEN 'Heartbeat' 
     WHEN description ILIKE '%Code Red Entry/Exit' THEN 'Code Red Entry/Exit' 
 etc... 
END

【问题讨论】:

  • 这里的搜索逻辑是什么?您想在这些字符串中找到某些关键字吗?或者,您只是想自己匹配整个字符串?
  • 我正在尝试自己找到确切的字符串。如果我有“TFTP 服务器心跳”——我需要输出“TFTP 服务器心跳”而不是“心跳”。否则,如果我有一些以“心跳”结尾但没有“TFTP 服务器”的文本 - 我需要获取“心跳”。实际上,我目前有 15 种不同的选项,但仅交叉匹配“TFTP 服务器心跳”和“心跳”

标签: regex string postgresql


【解决方案1】:

尝试如下使用正则表达式:

SELECT ARRAY_TO_STRING(REGEXP_MATCHES(description, '^\y(TFTP Server Heartbeat|Heartbeat|Code Red Entry/Exit)\y$', 'g'), '')
FROM yourTable
WHERE description ~ '\y(TFTP Server Heartbeat|Heartbeat|Code Red Entry/Exit)\y'

Demo

【讨论】:

  • 谢谢,但 xxx 或 yyy 不仅仅是单词——它们是一些未知的字符串。我想找到与最后一个词的完全匹配,如果是“心跳”/“TFTP 服务器心跳”,如果我有“TFTP 服务器心跳”,我想将它们与逻辑匹配 - 我需要输出“TFTP 服务器心跳”不是“心跳”;否则,如果我有一些以“心跳”结尾但没有“TFTP 服务器”的文本 - 我需要获取“心跳”。
  • @DenysSmakovskyi 嗯...我的回答没有假设 xxxyyy 实际上是什么,除了它们是您想要匹配的文本之前的单个非空白词。如果这个答案不符合您的期望,您应该更清楚地说明您的问题。
  • 我需要一个正则表达式替代下一个代码:CASE WHEN description ilike '%TFTP Server Heartbeat' then 'TFTP Server Heartbeat' WHEN description ilike '%Heartbeat' then 'Heartbeat' WHEN description ilike '%红色代码进入/退出”然后“红色代码进入/退出”等... END
  • 匹配项是否总是出现在列中的最后一项,或者它们可以隐藏在字符串中的任何位置?
  • 是的,它们是列中的最后一件事
【解决方案2】:

也许我完全错过了这条船,但听起来你只想要匹配的字符串,如果它是这三个字符串之一。

如果是这种情况并且您使用的是正则表达式,那么简单的子字符串会不起作用吗?

select
  substring (description from 'TFTP Server Heartbeat|Code Red Entry/Exit|Heartbeat')

样本数据的结果:

Heartbeat
Heartbeat
Code Red Entry/Exit
Code Red Entry/Exit
TFTP Server Heartbeat
TFTP Server Heartbeat

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    相关资源
    最近更新 更多