Cha*_*wla 2 regex sql oracle regexp-like
从 中查询CITY以元音(即 a、e、i、o 或 u)开头的名称列表STATION。
我的答案/尝试过的代码是:
select city from station where REGEXP_LIKE(city,'[^aeiou]+');
Run Code Online (Sandbox Code Playgroud)
但这似乎并不正确。
请帮我解决这个问题。
Zay*_*hin 18
使用SUBSTR
select t.city from station t where lower(SUBSTR(city,1,1)) in ('a','e','i','o','u')
Run Code Online (Sandbox Code Playgroud)
小智 8
另一种获取输出的方法
select distinct CITY from STATION where left(city,1) in ('a', 'e', 'i', 'o', 'u')
Run Code Online (Sandbox Code Playgroud)
所有 3 个都适用于 MySQL
SELECT DISTINCT(CITY)
FROM STATION
WHERE CITY REGEXP '^[aeiou]';
Run Code Online (Sandbox Code Playgroud)
SELECT DISTINCT(CITY)
FROM STATION
WHERE (CITY LIKE "A%")
OR (CITY LIKE "E%")
OR (CITY LIKE "I%")
OR (CITY LIKE "O%")
OR (CITY LIKE "U%");
Run Code Online (Sandbox Code Playgroud)
SUBSTR(string, start, length)。SUBSTR(CITY, 1, 1)表示从列中提取长度为1的位置1处的子串 CITY。SELECT DISTINCT(CITY)
FROM STATION
WHERE SUBSTR(CITY, 1, 1) IN ('A', 'E', 'I', 'O', 'U');
Run Code Online (Sandbox Code Playgroud)
正如 BackSlash 已经评论过的那样,您写错了REGEXP_LIKE模式,您应该将其更改为'^[aeiou].+',或者您甚至可以.+从模式中省略,因为您只对字符串的第一个字母(包含超过 1 个字符)感兴趣:
select city from station where REGEXP_LIKE(city,'^[aeiou]');
Run Code Online (Sandbox Code Playgroud)
请注意,只会返回以小写元音开头的电台!如果您还想包含大写元音而不是将它们添加到您的模式中:
select city from station where REGEXP_LIKE(city,'^[aeiouAEIOU]');
Run Code Online (Sandbox Code Playgroud)
或使用标志指定REGEXP_LIKE输入模式不区分大小写的内部调用'i',如下所示:
select city from station where REGEXP_LIKE(city,'^[aeiou]', 'i');
Run Code Online (Sandbox Code Playgroud)
感谢 MT0 的有用评论!
我希望我们有所帮助!