Python Forum
regex, counting occurences
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
regex, counting occurences
#1
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
Reply
#2
Quote:Everything i try fails
what have you tried?
Reply
#3
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!
Reply
#4
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
>>>
Reply
#5
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Count occurences in a string and add to a list using loops Leyo 4 1,690 Mar-11-2022, 03:52 PM
Last Post: Leyo
  Quick Lists Question (Count Occurences) EwH006 12 10,857 Nov-17-2016, 11:59 AM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020