views:

120

answers:

3

A table contains the string "Hello world!"

Thinking of * as the ordinary wildcard character, how can I write a REGEXP that will evalute to true for 'W*rld!' but false for 'H*rld!' since H is part of another word. 'W*rld' should evalute to false as well because of the trailing '!'

+2  A: 

If you are just looking to match the word world, then do this:

SELECT * FROM `table` WHERE `field_name` LIKE "w_rld!";

The _ allows for a single wildcard character.

Edit: I realize the OP requested this solution with REGEXP, but since the same result can be achieved without using regular expressions, I provided this as viable solution that should perform faster than a REGEXP.

Doug Neiner
Agreed, but since the result could be achieved *without* REGEXP, wouldn't the right way in a production environment be to use the solution without REGEXP?
Doug Neiner
So which is faster? `REGEXP` or `LIKE`?
Nirmal
@Doug Neiner: Sure you should prefer LIKE over REGEXP if either would work. But what if the examples he gave were just simplified examples and in reality he has to match more complex things that can't be done with a LIKE? The performance of LIKE is irrelevant if it gives the wrong result.
Mark Byers
@Nirmal LIKE is considerably faster in my quick little tests locally.
Doug Neiner
@Mark, you are correct of course. However, if the faster solution does help the OP or another searcher speed up their query then I think it still has value. Especially since @OMG Ponies and your answer is so clear, and yours has been accepted.
Doug Neiner
+6  A: 

Use:

WHERE column REGEXP 'W[[:alnum:]]+rld!'

Alternately, you can use:

WHERE column RLIKE 'W[[:alnum:]]+rld!'
  • RLIKE is a synonym for REGEXP
  • [[:alnum:]] will allow any alphanumeric character, [[:alnum:]]+ will allow multiples
  • REGEXP \ RLIKE is not case sensitive, except when used with binary strings.

Reference: MySQL Regex Support

OMG Ponies
Edited to add that REGEXP is not case sensitive...
OMG Ponies
+1 Great answer
Doug Neiner
Thank you Ponies! Seems like there is a lot to learn.
Nirmal
+1  A: 

You can use regular expressions in MySQL:

SELECT 'Hello world!' REGEXP 'H[[:alnum:]]+rld!'
0
SELECT 'Hello world!' REGEXP 'w[[:alnum:]]+rld!'
1

More information about the syntax can be found here.

Mark Byers
Thank you, works like a charm.
Ed Taylor