mysqlrlike

How to use RLIKE/REGEXP patterns .* in MySQL


Question: Query the list of CITY names from STATION which have vowels (i.e., a, e, i, o, and u) as both their first and last characters. Your result cannot contain duplicates.

I found an answer edited by @Mureinik, (thank you! it is very helpful!)

SELECT DISTINCT CITY FROM STATION WHERE CITY RLIKE '^[aeiouAEIOU].*[aeiouAEIOU]$';

I am confused that, the question is asking about both their first and last characters is aeiou, why can't I just use

CITY RLIKE '^[aeiouAEIOU][aeiouAEIOU]$'

However, when I take out the . and *, it is shown wrong answer.

Why do we need to use . and * in this question? Does . and * always use together?

There is another question: Query the list of CITY names from STATION that do not start with vowels. Your result cannot contain duplicates.

SELECT DISTINCT CITY FROM STATION WHERE CITY NOT RLIKE '^[aeiouAEIOU].*$'; 

Why use [aeiouAEIOU] twice in the first question, only use once in the second?


Solution

  • CITY RLIKE '^[aeiouAEIOU][aeiouAEIOU]$'
    

    This will only match city names with exactly two characters, both vowels.

    In regular expressions, a set of characters in square brackets like [aeiouAEIOU] matches exactly one character.

    You have nothing in between the two square-bracketed sets, so there must not be any characters in between in the strings that match.