Postgres函数返回REGEXP_MATCHES结果

发布于 2025-01-31 11:08:57 字数 535 浏览 4 评论 0原文

我正在尝试编写一些PostgreSQL功能,以帮助我解析诸如“ 30GI”或“ 25TI”之类的字符串值。我尝试过,但无法正确理解语法,也无法弄清楚第一个函数的返回类型应该是什么。

CREATE FUNCTION get_matches(VARCHAR) RETURNS ARRAY(VARCHAR) AS 
SELECT (regexp_matches ($1, '(\d+)([KGTM]i)'));

CREATE FUNCTION get_amount(ARRAY(VARCHAR)) RETURNS VARCHAR AS 
SELECT get_matches($1)[1];

CREATE FUNCTION get_units(ARRAY(VARCHAR)) RETURNS VARCHAR AS 
SELECT get_matches($1)[2];

Postgres版本: postgresql 13.2在x86_64-pc-linux-gnu上,由GCC(Debian 8.3.0-6)8.3.0,64位 使用PGADMIN4测试我的功能。

I am trying to write some postgresql functions to help me parse a string value like "30Gi" or "25Ti". I tried this, but can't get the syntax right, and can't figure out what the return type should be for the first function.

CREATE FUNCTION get_matches(VARCHAR) RETURNS ARRAY(VARCHAR) AS 
SELECT (regexp_matches ($1, '(\d+)([KGTM]i)'));

CREATE FUNCTION get_amount(ARRAY(VARCHAR)) RETURNS VARCHAR AS 
SELECT get_matches($1)[1];

CREATE FUNCTION get_units(ARRAY(VARCHAR)) RETURNS VARCHAR AS 
SELECT get_matches($1)[2];

Postgres version:
PostgreSQL 13.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
Testing my functions using pgAdmin4.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╄→承喏 2025-02-07 11:08:57

您可以在一个查询中返回两个。以下返回2列大小的,用于有效表达式。验证参数的正确格式(通过REGEX)后,它基本使用Regexp_replace返回每个组件。

create or replace function size_units(p_size_units text)
     returns table ( size  integer
                   , units text
                   )
    language sql
as $; 
   select regexp_replace(p_size_units, '^(\d+)([KGTM]i)

如果需要,您可以在Select语句中使用结果。 (请参阅

, '\1')::integer , regexp_replace(p_size_units, '^(\d+)([KGTM]i)

如果需要,您可以在Select语句中使用结果。 (请参阅

, '\2') where p_size_units ~ '^\d+[KGTM]i

如果需要,您可以在Select语句中使用结果。 (请参阅

; $;

如果需要,您可以在Select语句中使用结果。 (请参阅

You can get both returned in a single query. The following returns a table of 2 columns size and units for valid expressions. After validating the parameter is correctly formatted (via regex) it uses basically the same with regexp_replace to return each component.

create or replace function size_units(p_size_units text)
     returns table ( size  integer
                   , units text
                   )
    language sql
as $; 
   select regexp_replace(p_size_units, '^(\d+)([KGTM]i)

You can use the results in a select statement if desired. (see demo).

, '\1')::integer , regexp_replace(p_size_units, '^(\d+)([KGTM]i)

You can use the results in a select statement if desired. (see demo).

, '\2') where p_size_units ~ '^\d+[KGTM]i

You can use the results in a select statement if desired. (see demo).

; $;

You can use the results in a select statement if desired. (see demo).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文