Return Only number from a string if it contains numbers

后端 未结 3 1477
深忆病人
深忆病人 2021-01-28 07:21

For example,
string is abc123CD need to find out a method to read only numbers in the string
i.e.

  select a_postgres_function(\'a         


        
相关标签:
3条回答
  • 2021-01-28 08:02

    If you want to get all digit characters from the string (not just the first group), it is easier to remove all characters, which aren't a digit:

    select regexp_replace('abc123CD45ef', '[^\d]+', '', 'g');
    
    -- regexp_replace
    -- --------------
    --    '12345'
    
    0 讨论(0)
  • 2021-01-28 08:03

    Try this:

    select (regexp_matches('abc123CD', '\d+'))[1];
    

    Since regexp_matches returns array of text, you should access the first element by [1].

    0 讨论(0)
  • 2021-01-28 08:20

    As per ntalbs's Answer


    Wrap that query into a Function

    create or replace function shownums(text) returns integer as 
    $$
    select (regexp_matches($1,'\d+'))[1]::int; 
    $$
    language sql;
    
    0 讨论(0)
提交回复
热议问题