匹配的正则表达式以

标签 regex postgresql

我需要将表设置属性 MATCH 更新为 True,其中 attribute_a 以 attribute_b 的值开头。

不知何故,我无法在 Postgresql 中获得正确的语法来进行此模式匹配。

UPDATE table   
   SET  match= True  
WHERE attribute_a ~ '^attribute_b' ;

例如 MATCH TRUE:attribute_a = 纳尔逊·曼德拉; attribute_b = '纳尔逊'

最佳答案

您不需要模式匹配,请使用left() ,例如:

with my_table(attribute_a, attribute_b) as (
values 
    ('Nelson Mandela', 'Nelson'),
    ('Donald Trump', 'Donald Duck'),
    ('John Major', 'John M')
)

select *
from my_table
where attribute_b = left(attribute_a, length(attribute_b));

  attribute_a   | attribute_b 
----------------+-------------
 Nelson Mandela | Nelson
 John Major     | John M
(2 rows)

如果您绝对想使用正则表达式,则必须使用 concat()format() 构建模式,如下所示:

select *
from my_table
where attribute_a ~ concat('^', attribute_b)
-- where attribute_a ~ format('^%s', attribute_b)

关于匹配的正则表达式以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42861852/

相关文章:

python - SQLAlchemy 继承不起作用

postgresql - 如何通过 .sh 文件添加 Postgres 扩展

sql - 是否可以在 PostgreSQL 中创建可为空的外键约束?

regex - 匹配正则字符串

java - 单词相似度的正则表达式 "n letter difference"

javascript - Factor1-1.25/factor2-2.5/的正则表达式

php - 帮助破解 Gruber 的自由 URL 正则表达式

regex - System.RegularExpressions.TRegEx 是线程安全的吗?

postgresql - 尽管字符串是有效的 UTF8,但字节序列无效

python - django 扩展内置用户模型不允许在管理员中登录