Postgres query to check a string is a number

前端 未结 6 1334

Can anyone tell me the query to check whether a string is a number(double precision). It should return true if the string is number. else it should return false.

con

相关标签:
6条回答
  • 2020-12-01 18:09

    I think the easiest way would be a regular expression match:

    select '12.41212' ~ '^[0-9\.]+$'
    => true
    
    select 'Service' ~ '^[0-9\.]+$'
    => false
    
    0 讨论(0)
  • 2020-12-01 18:18

    If you want to check with exponential , +/- . then the best expression is :

    ^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$
    

    resulting in:

    select '12.41212e-5' ~ '^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$' ;
    

    as true.

    The expression is from: https://www.regular-expressions.info/floatingpoint.html

    You can check for other types of numbers, for example if you expect decimal, with a sign.

     select '-12.1254' ~ '^[-+]?[0-9]*\.?[0-9]+$';
    
    0 讨论(0)
  • 2020-12-01 18:22
    select s1 ~ '^\d+$';
    select s2 ~ '^\d+$';
    
    0 讨论(0)
  • 2020-12-01 18:31

    I fixed the regular expression that a_horse_with_no_name has suggested.

    SELECT '12.41212' ~ '^\d+(\.\d+)?$'; -- true
    SELECT 'Service' ~ '^\d+(\.\d+)?$'; -- false
    
    0 讨论(0)
  • 2020-12-01 18:31

    If you only need to accept double precision numbers, this should work fine:

    select '12.41212' ~ '^\d+\.?\d+$'; -- true
    select 'Service' ~ '^\d+\.?\d+$'; -- false
    

    This would also accept integers, and negative numbers:

    select '-1241212' ~ '^-?\d+\.?\d+$'; -- true
    
    0 讨论(0)
  • 2020-12-01 18:34

    I would like to propose another suggestion, since 12a345 returns true by ns16's answer.

    SELECT '12.4121' ~ '^\d+(\.\d+)?$'; #true
    SELECT 'ServiceS' ~ '^\d+(\.\d+)?$'; #false
    SELECT '12a41212' ~ '^\d+(\.\d+)?$'; #false
    SELECT '12.4121.' ~ '^\d+(\.\d+)?$'; #false
    SELECT '.12.412.' ~ '^\d+(\.\d+)?$'; #false
    
    0 讨论(0)
提交回复
热议问题