I'm trying to count the words in a string using regex in Oracle 10g. I've been trying this
select *
from books
where REGEXP_LIKE(title, '[ ]{2}');
so that its returning titles with at least 3 words in the title.
I'm trying to count the words in a string using regex in Oracle 10g. I've been trying this
select *
from books
where REGEXP_LIKE(title, '[ ]{2}');
so that its returning titles with at least 3 words in the title.
INSTR is also a viable option. By looking for the second occurrence of a space, that will indicate that the string has at least 3 words.
WITH
books
AS
(SELECT 'Tom Sawyer' title FROM DUAL
UNION ALL
SELECT 'A tale of two cities' FROM DUAL
UNION ALL
SELECT 'The Little Prince' FROM DUAL
UNION ALL
SELECT 'Don Quixote' FROM DUAL)
SELECT title
FROM books
WHERE instr(title, ' ', 1, 2) > 0;
If you do with to stick with regex, the regex expression below can be used to find books that have 3 or more words.
WITH
books
AS
(SELECT 'Tom Sawyer' title FROM DUAL
UNION ALL
SELECT 'A tale of two cities' FROM DUAL
UNION ALL
SELECT 'The Little Prince' FROM DUAL
UNION ALL
SELECT 'Don Quixote' FROM DUAL)
SELECT title
FROM books
WHERE REGEXP_LIKE (title, '(\S+\s){2,}');
(Thanks @Littlefoot for the books!)
INSTR(title, ' ', 1, 2) is looking for the second occurrence of a space from the 1st character in the string title.REPLACE does the job (with some calculation).
SQL> with books as
2 (select 'Tom Sawyer' title from dual union all
3 select 'A tale of two cities' from dual union all
4 select 'The Little Prince' from dual union all
5 select 'Don Quixote' from dual
6 )
7 select title
8 from books
9 where length(title) - length(replace(title, ' ', '')) >= 2;
TITLE
--------------------
A tale of two cities
The Little Prince
SQL>
The below one is simple and easy to understand (works on 11g and later):
The below is just to create some sample data
create table books as
with tab as
(
select 'Tom Sawyer' title from dual
union all
select 'A tale of two cities' from dual
union all
select 'The Little Prince' from dual
union all
select 'The_Little_Prince' from dual
union all
select 'Don Quixote' from dual
union all
select null from dual
)
select title
from tab;
The below is your solution to get those titles that have at least 3 words in it
select title
from books
where regexp_count(title, '\w+') > 2
Output: