Regular Expression in PostgreSQL
Regular Expression is a very powerful tools for programming language like java, .NET, PHP , Perl…or even PostgreSQL.
Here i write some basic examples to show how to use regular expression in PostgreSQL.
1) isdigit function – This function is missing in PostgreSQL, as this is a built-in function in others database.
This is a very useful function to validate only number allow. However we can create isdigit function ourself in PostgreSQL.
1 2 3 4 5 6 7 | CREATE OR REPLACE FUNCTION isdigit(text) RETURNS BOOLEAN AS ' select $1 ~ ''^(-)?[0-9]+$'' as result ' LANGUAGE SQL; --test function SELECT isdigit('1') --return true SELECT isdigit('A') --return false |
2) isString function – This function is missing in PostgreSQL as well, as this is a built-in function in others database.
This is a very useful function to validate only string allow. However we can create isString function ourself in PostgreSQL.
1 2 3 4 5 6 7 | CREATE OR REPLACE FUNCTION isString(text) RETURNS BOOLEAN AS ' select $1 ~ ''^(-)?[a-zA-Z]+$'' as result ' LANGUAGE SQL; --test function SELECT isString('1') --return false SELECT isString('A') --return true |
3) isIPAddress function – I do not think this is a built-in function in other database. This functions is use to validate IP Address allow.
Example A
1 2 3 4 5 6 7 8 9 | --check ipaddress CREATE OR REPLACE FUNCTION isIPAddress(text) RETURNS BOOLEAN AS ' select $1 ~ ''^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'' as result ' LANGUAGE SQL; --test function SELECT isIPAddress('202.111.0.1') --return true SELECT isIPAddress('202.ZZZ.0.A') --return false SELECT isIPAddress('202.11199999999.1.100') --return true |
Example B
1 2 3 4 5 6 7 8 | CREATE OR REPLACE FUNCTION isIPAddressStrict(text) RETURNS BOOLEAN AS ' select $1 ~ ''^[0-9]?[0-9]?[0-9]?\.[0-9]?[0-9]?[0-9]?\.[0-9]?[0-9]?[0-9]?\.[0-9]?[0-9]?[0-9]?$'' as result ' LANGUAGE SQL; --test function SELECT isIPAddressStrict('202.111.0.1') --return true SELECT isIPAddressStrict('202.ZZZ.0.A') --return false SELECT isIPAddressStrict('202.11199999999.1.100') --return false |
Wow, impressive right? Actually Regular Expression is more powerful than above simple function. It is worth to invest time to study on it. Please go here if you want to know more about it
http://en.wikipedia.org/wiki/Regular_expression
Please share your example to me also, if you do not mind. Thanks
It work to me,think you!