简体   繁体   English

从Postgres中的字符串中提取特定长度的数字

[英]Extracting number of specific length from a string in Postgres

I am trying to extract a set of numbers from comments like 我正在尝试从评论中提取一组数字

"on april-17 transactions numbers are 12345 / 56789"
"on april-18 transactions numbers are 56789"
"on may-19 no transactions"

Which are stored in a column called "com" in table comments 哪些存储在表注释的名为“ com”的列中

My requirement is to get the numbers of specific length. 我的要求是获取特定长度的数字。 In this case length of 5, so 12345 and 56789 from the above string separately, It is possible to to have 0 five digit number or more more than 2 five digit number. 在这种情况下,长度为5,因此上述字符串的长度分别为12345和56789,可以有0个五位数或大于2个五位数。

I tried using regexp_replace with the following result, I am trying the find a efficient regex or other method to achieve it 我尝试将regexp_replace与以下结果一起使用,我正在尝试寻找一种有效的regex或其他方法来实现它

select regexp_replace(com, '[^0-9]',' ', 'g') from comments;

                      regexp_replace                   
----------------------------------------------------
          17                          12345   56789

I expect the result to get only 我希望结果只会得到

column1 | column2
12345     56789

There is no easy way to create query which gets an arbitrary number of columns: It cannot create one column for one number and at the next try the query would give two. 创建具有任意列数的查询没有简单的方法:它无法为一个数字创建一列,而在下一次尝试中查询将给出两列。


For fixed two columns: 对于固定的两列:

demo:db<>fiddle 演示:分贝<>小提琴

SELECT 
   matches[1] AS col1,
   matches[2] AS col2
FROM ( 
    SELECT
        array_agg(regexp_matches[1]) AS matches
    FROM
        regexp_matches(
            'on april-17 transactions numbers are 12345 / 56789', 
            '\d{5}',
            'g'
        )
) s
  1. regexp_matches() gives out all finds in one row per find regexp_matches()在每个查找的一行中给出所有查找
  2. array_agg() puts all elements into one array array_agg()将所有元素放入一个数组
  3. The array elements can be give out as separate columns. 数组元素可以作为单独的列给出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM