如何判断一个字符串是合法的数值、浮点或者科学计数的格式?
首先想到的是正则表达式。
一些匹配规则如下:
"^\d+$" //非负整数(正整数 + 0) "^[0-9]*[1-9][0-9]*$" //正整数 "^((-\d+)|(0+))$" //非正整数(负整数 + 0) "^-[0-9]*[1-9][0-9]*$" //负整数 "^-?\d+$" //整数 "^\d+(\.\d+)?$" //非负浮点数(正浮点数 + 0) "^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$" //正浮点数 "^((-\d+(\.\d+)?)|(0+(\.0+)?))$" //非正浮点数(负浮点数 + 0) "^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$" //负浮点数 "^(-?\d+)(\.\d+)?$" //浮点数PostgreSQL支持正则表达,UDF函数,可以完成这项工作。
将正则表达式写成函数即可完成对应的判断,例子
create or replace function check_int(text) returns boolean as $$ select $1 ~ '^\d+$'; $$ language sql strict;验证
postgres=# select check_int('1'); check_int ----------- t (1 row) postgres=# select check_int('123'); check_int ----------- t (1 row) postgres=# select check_int('123.1'); check_int ----------- f (1 row) postgres=# select check_int(''); check_int ----------- f (1 row) postgres=# select check_int('abc'); check_int ----------- f (1 row)如果不区分格式的话,可以使用PostgreSQL的强制转换以及函数来处理,使用异常捕获即可。
postgres=# create or replace function check_numeric(text) returns boolean as $$ declare begin perform ($1)::numeric; return true; exception when others then return false; end; $$ language plpgsql strict; CREATE FUNCTION验证
postgres=# select check_numeric('12..1'); check_numeric --------------- f (1 row) postgres=# select check_numeric('12.1'); check_numeric --------------- t (1 row) postgres=# select check_numeric('12.1a'); check_numeric --------------- f (1 row)如果你要强转异常的值,可以自定义cast进行转换,例子.
postgres=# select '12.1a.1'::text::numeric; ERROR: invalid input syntax for type numeric: "12.1a.1" postgres=# create or replace function text_to_numeric(text) returns numeric as $$ select to_number($1,'9999999999999999999999999.99999999999999'); $$ language sql strict; CREATE FUNCTION postgres=# select text_to_numeric('12.1a.1'); text_to_numeric ----------------- 12.11 (1 row) postgres=# create cast (text as numeric) with function text_to_numeric(text) ; CREATE CAST postgres=# select '12.1a.1'::text::numeric; numeric --------- 12.11 (1 row)