0

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 '!'

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

5 Comments

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?
So which is faster? REGEXP or LIKE?
@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.
@Nirmal LIKE is considerably faster in my quick little tests locally.
@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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.