regex - 正则表达式用于在一个字符串包含另一个字符串时查找两个字符串之一

标签 regex string postgresql

它将在 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

最佳答案

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

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'

enter image description here

Demo

关于regex - 正则表达式用于在一个字符串包含另一个字符串时查找两个字符串之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54414250/

相关文章:

string - Golang 在字符串 slice 中追加字符串

postgresql - 如何强制客户端对 postgresql 使用 SSL?

html - 解析 postgresql 查询中的 html 字段

python - 如何在Python列表中使用正则表达式

javascript 正则表达式 2 个可能的值

java - 我希望从 Java 中的匹配模式中提取值

postgresql - 创建 PostGIS 我的第一个表

c# - 匹配冒号和分号之间的值

c - 在C中进行游戏的while循环?

string - 按端口号对 IPv4 地址进行排序