postgresql 字符串匹配,以abc:skp开头:在那之后只有一个数字

bvk5enib  于 2023-01-30  发布在  PostgreSQL
关注(0)|答案(1)|浏览(234)

我想对应该以abc:skp开头的字符串进行字符串匹配:并且在那之后只有数字。
这就是我希望在PostgreSQL上实现的。
例如,用于检查PL/pgSQL块中的true或false的字符串

  1. abc:skp:293043204 --此操作有效并返回true
  2. abc:skp:23 hj 29490--这是无效的,并返回false
    如何在PL/pgSQL块中执行此操作,即
do $$
<<block_2740>>
---
end $$`

我已经尝试了以下的东西,但不工程的第二个

if TEXTREGEXEQ(item_pguid,'abc:skp:([0-9]+)') then 
-- checking
end if;
oxf4rvwz

oxf4rvwz1#

参见https://www.postgresql.org/docs/13/functions-matching.html
如果愿意,您可以使用~文本操作符,或者使用regexp_matches函数。下面是使用regexp_matches的示例。我还更正了您的正则表达式。您缺少终止匹配$

create or replace function sample_regex_match() returns void as $$

    declare
        sample_strings text[];
    BEGIN
    sample_strings:=array['abc:skp:293043204','abc:skp:456','abc:skp:789','dontmatch','abc:skp:23hj29490'];
    for i in 1..array_length(sample_strings,1) loop
        if cardinality(regexp_matches(sample_strings[i],'abc:skp:([\d]+)$'))>0 then
            raise notice 'The string "%" matches the regex', sample_strings[i];
        else
            raise notice 'The string "%" does not match the regex', sample_strings[i];
        end if;
    end loop;
END $$ language plpgsql;
select sample_regex_match();

这将输出

The string "abc:skp:293043204" matches the regex
The string "abc:skp:456" matches the regex
The string "abc:skp:789" matches the regex
The string "dontmatch" does not match the regex
The string "abc:skp:23hj29490" does not match the regex

相关问题