【问题标题】:use a regex capture in a pgSQL select在 pgSQL 选择中使用正则表达式捕获
【发布时间】:2013-08-27 14:28:00
【问题描述】:

我从未在 SQL 中使用过正则表达式。如果我在 javascript 中捕获这样的内容,我如何像使用 javascript match() 方法中的第二个元素一样引用 pgSQL 中的捕获?

var str = 'thomas-var1="SOME VAL1" thomas=var2="SOME VAL2" thomas-var-3="the value i want" thomas-var-4="SOME_VAL4"';

var re = /thomas-var-3="(.+?)"/i;

var new_str = str.match(re);

console.log(new_str[1]);

我怎样才能把它放到SELECT 语句中,这样我就可以说,从thomas-var-3 检索值"the value i want"

SELECT * FROM forms WHERE name LIKE '%bill%' AND category = MY REGEX CAPTURE

渲染类似“

SELECT * FROM forms WHERE name LIKE '%bill%' AND category ='the value i want'

【问题讨论】:

  • 你能发布一些示例输入和输出吗? (还有——你读过the documentation吗?)
  • @ruakh 已更新。谢谢。
  • 您是否直接从 javascript 与 postgres 交互?您使用什么技术从 javascript 到 SQL 语句?
  • @JDiPierro Javascript 不参与其中。这是我知道如何编写模式的唯一方法,所以我在问题中使用它来演示我试图用 SQL 做什么。
  • 啊,我明白了。我对您当时要匹配的内容感到困惑..您要填写的匹配项..您是否希望 postgres 在搜索时将其从其他列中拉出?

标签: sql regex postgresql


【解决方案1】:

您可以不使用正则表达式,而是使用hstore extension,例如:

str := 'thomas-var1="SOME VAL1" thomas-var2="SOME VAL2" thomas-var-3="the value i want"'
str := replace(replace(str, '=', '=>'), '" ', '", ')

select *
from forms
where name like '%bill%' and category = hstore(str)->'thomas-var-3'

【讨论】:

    【解决方案2】:

    使用 subselect 和 substring 方法你应该能够实现你想要的:

    SELECT * 
    FROM firstTable 
    WHERE parentCat = (SELECT cat 
                       FROM secondTable 
                       WHERE cat in substring(column_to_capture_from from 'thomas-var-3="(.+?)' ));
    

    来自http://www.regular-expressions.info/postgresql.html

    如果有匹配,并且正则表达式有一个或多个捕获组,则返回第一个捕获组匹配的文本。

    【讨论】:

    • 使用IN而不是=在子选择返回多于一行的情况下更安全。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多