Count occurrences of character in a string using MySQL

前端 未结 3 1697
旧时难觅i
旧时难觅i 2021-01-03 22:55

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\'

相关标签:
3条回答
  • 2021-01-03 23:45
    select *  
    from table  
    where  LENGTH(name) - LENGTH(REPLACE(name, 'a', '')) between 1 and 2
    

    Updated to use between.

    0 讨论(0)
  • 2021-01-03 23:49

    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.

    0 讨论(0)
  • 2021-01-03 23:49

    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
    /
    
    0 讨论(0)
提交回复
热议问题