【问题标题】:Return Only number from a string if it contains numbers如果字符串包含数字,则仅返回字符串中的数字
【发布时间】:2014-10-30 03:45:00
【问题描述】:

例如
字符串是abc123CD需要找出一个方法来读取字符串中的数字

  select a_postgres_function('abc123CD')

  ------
  Result
  ------
  123

我的尝试

 select substring('abc123CD' from '%#"^[0-9]+$#"%' for '#')

【问题讨论】:

    标签: sql regex postgresql substring


    【解决方案1】:

    试试这个:

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

    由于regexp_matches 返回文本数组,您应该通过[1] 访问第一个元素。

    【讨论】:

      【解决方案2】:

      根据ntalbs's Answer


      将该查询包装成一个函数

      create or replace function shownums(text) returns integer as 
      $$
      select (regexp_matches($1,'\d+'))[1]::int; 
      $$
      language sql;
      

      【讨论】:

        【解决方案3】:

        如果您想从字符串中获取所有数字字符(不仅仅是第一组),删除所有不是数字的字符会更容易:

        select regexp_replace('abc123CD45ef', '[^\d]+', '', 'g');
        
        -- regexp_replace
        -- --------------
        --    '12345'
        

        【讨论】:

          猜你喜欢
          • 2013-01-16
          • 1970-01-01
          • 1970-01-01
          • 2019-03-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-14
          相关资源
          最近更新 更多