Python Forum

Full Version: regex, counting occurences
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,


I am pretty new with regex, i am trying to write a pattern that would check if there is a an odd number of specific characters within a string. I want to get true if i just have g,h or i r in a string and if i have odd number of g and h ( the sum of both of the occurences). Everything i try fails...What would be the best approach for that kind of issue?

Thank you
Regards,
Othniel
Quote:Everything i try fails
what have you tried?
Thank you for answering.
I had no idea how to even begin, because i did not know how to say an odd number of occurrences.
So i try just to put an odd number between 0 and 10. That is what i put:
'(^[g-i]+$)([g,i]{0,1,3,5,7,9})'
It does not work obviously...

Thank you for your help!
you really don't need regex for this.
>>> def isodd(val):
...     return bool(len(val) % 2)
...
>>> stra = 'I have odd number of characters'
>>> strb = 'I have an even number of characters.'
>>> len(stra)
31
>>> len(strb)
36
>>> isodd(stra)
True
>>> isodd(strb)
False
>>>
It is possible to do it with regex (even when is completely overkill) and as homework to learn regex is good.

As a hint, try to create a regex that matches 0 or more times a pair of letters... so ffff will be match as ff ff but ggg will not. To request exact match you can look for the start and end of the input string with ^ and $ or check that the length of the matched text is equal to the input.