如何判斷字符串是否為合法數值、浮點、科學計數等格式
背景
如何判斷一個字符串是合法的數值、浮點或者科學計數的格式?
首先想到的是正則表達式。
一些匹配規則如下:
"^\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)
補充
補充
//正則匹配
匹配中文字符的正則表達式: [\u4e00-\u9fa5]
匹配雙字節字符(包括漢字在內):[^\x00-\xff]
匹配空行的正則表達式:\n[\s| ]*\r
匹配HTML標記的正則表達式:/<(.*)>.*<\/\1>|<(.*) \/>/
匹配首尾空格的正則表達式:(^\s*)|(\s*$)(像vbscript那樣的trim函數)
匹配Email地址的正則表達式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
匹配網址URL的正則表達式:https://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
最後更新:2017-04-12 23:25:18