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/

相关文章:

java - 正则表达式 [A-Za-z !,?. _'@]+ returns 0 matches while [ !,?._' @]+ 返回 10?

python - Pyramid 替换 URL Matchdict 中的双正斜杠

python - cython中不同字符串的相同内存地址

JavaScript - 使用数组检查字符串

javascript - 如果字段为空则跳过

postgresql - 使用变量传递的名称创建模式

SQL - 如果数组包含特定项目则过滤行

Python RegEx 匹配异常

database - 将 PostgreSQL 数据库复制到另一台服务器

java - 正则表达式替换为增量