26

Example Words: a, akkka, akokaa, kokoko, kakao, oooaooa, kkako, kakaoa

I need the regexp witch gives words with 2 or less 'a' but not the words without 'a'

Result: a, akka, kakao, oooaooa, kkako

Ok actually I am using:

SELECT word FROM dictionary_gr WHERE word REGEXP 'λ{2,3}' LIMIT 0 , 30

this returns 0 lines there are words with 2 λ's and 3 λ's

1

3 Answers 3

43
select *  
from table  
where  LENGTH(name) - LENGTH(REPLACE(name, 'a', '')) between 1 and 2

Updated to use between.

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

12 Comments

Example: baaa => b. LENGTH(b) <= 1. But original string contains more than 2 'a's.
@simon that is a completely different query than what I am using. Further why are you taking the length of b?
@Woot4Moo Why? You first replace all 'a's with ''. After that you retrieve the length of the string without 'a's. Am I getting this wrong?
@Simon you were correct, I missed the initial subtraction, good eye :)
@Woot4Moo Now it's nearly perfect :) it must be greater than zero. You can use the BETWEEN-Operator with the operands 1 and 2
|
2

I don't know what MySQL supports in terms of lookaround assertions, but the following will do the trick:

^(?=.*a.*a?.*)(?!.*a.*a.*a.*).*$

We have a lookahead assertion that matches 1 or 2 a characters in the string. Then we have a negative lookahead that disregards 3 or more as anywhere in the string. Then the final pattern just matches the whole string, providing the first two assertions are satisfied.

If MySQL doesn't support lookarounds, then @Woot4Moo's answer would be the way to go.

Comments

-3

Quick and dirty:

Select word, number_of_as From
(
 Select 'akkka' word, REGEXP_COUNT('akkka', 'a') number_of_as From dual
)
Where number_of_as <= 2
/

3 Comments

REGEXP_COUNT is Oracle (11g and later), not MySQL.
Look here-MySQL 5.1 Reference Manual - Regular Expressions: dev.mysql.com/doc/refman/5.1/en/regexp.html
There is no mention of REGEXP_COUNT in the MySQL manual (the page you linked), nor any function like it. As I say, it's an Oracle function that was introduced in 11g: docs.oracle.com/cd/B28359_01/server.111/b28286/functions135.htm

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.