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.
Advertisement
Answer
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!)