130 likes | 252 Vues
SQL. Regular Expressions. REGEXP. Mysql supports regular expressions Keyword is REGEXP Select columns from tableName where columnName regexp ‘someRegularExpression’. REGEXP.
                
                E N D
SQL Regular Expressions
REGEXP • Mysql supports regular expressions • Keyword is REGEXP • Select columns from tableName where columnName regexp ‘someRegularExpression’
REGEXP • Concept and syntax are somewhat similar to the regular expression concept and syntax in various programming languages (Perl, PHP, Java, ..)
REGEXP • Customers having a p in their name • Select * from customer where name regexp ‘p’; • Customers containing pre in their name • Select * from customer where name regexp ‘pre’;
REGEXP • Use of meta-characters enable more powerful SQL queries • [ ]  in this set • Customers who have a, b, or c in their name • Select * from customer where name regexp ‘[abc]’;
REGEXP • [^ ]  not in this set • Customers who have a character that is not a to x in their name • Select * from customer where name regexp ‘[^a-x]’;
REGEXP • ^  matches at beginning • $  matches at the end • .  matches any character • *  0 or more • Customers who have a name that starts with a letter between d and z and ends with e • Select * from customer where name regexp ‘^[d-z].*e$’;
REGEXP • Do not confuse • ^ inside the square brackets, i.e. [^ ] not in set • With • ^  matches at the beginning
REGEXP • ?  0 or 1 • +  1 or more • ab | xyz  matches ab or xyz • Customers who have a name that starts with a or c • Select * from customer where name regexp ‘^(a|c)’;
REGEXP • {n}  n instances of character • {m, n}  between m and n (included) instances of character • Customers who have a name that contains 2 consecutive s • Select * from customer where name regexp ‘s{2}’;
REGEXP • [a-z] or [[:alpha:]]  matches a letter • [0-9] or [[:digit:]]  matches a digit • Customers who have an address that contains a digit • Select * from customer where address regexp ‘[0-9]’;
REGEXP • [[:character_class:]]  matches a character belonging to the class character_class • Character_class could be: digit, alpha, alnum, space, blank, lower, upper, .. • http://dev.mysql.com/doc/refman/5.0/en/regexp.html
REGEXP • Customers from a city that has a white space character in it • Select * from customer where city regexp ‘[[:space:]]’; • Could also use: • Select * from customer where city regexp ‘ ’;