1

Is there a way to check to see if each unique character occurs the same amount of times? Soley using the regex language or do I have use regex and str.count to find a valid match?

This is what I'm expecting the results to be:

xy     -> valid
xxyy   -> valid
xxxyyy -> valid
xyy    -> not valid
xxy    -> not valid

I know I can do something like:

matches = re.match(r"^x+y+$", myTestStr)

But is there any way I have the '+' token for 'x' be the same as the '+' token for 'y'? I've also tried working with groups but have had no luck there either.

  • 1
    Cannot be done using pure regex in `re` module. Might be possible in PCRE `regex` module. – anubhava Mar 04 '20 at 20:28
  • 1
    regex is not meant to do this. There could be some really weird ways to do that. But actual regex is not an easy way to do it – Superluminal Mar 04 '20 at 21:08
  • 1
    With `regex` module, it is the same as in PCRE. See the [original thread](https://stackoverflow.com/questions/3644266/how-can-we-match-an-bn-with-java-regex) – Wiktor Stribiżew Mar 04 '20 at 21:29

1 Answers1

1

You could use recursion for this, but to be honest it is not the best practise for the task. Regex are not meant to be recursive. And recursiion, as far as I remember is not insluded in the standart re python module. I think you need the regex module then

if empty should be allowed:

\b(x(?1)y|)\b

if empty string should not be allowed

\b(x(?1)y|(?<=x)(?=y))\b

demo https://regex101.com/r/x0McMc/3

if you have a maximum fixed length of the string you could also do this (max length 4 in example):

\b(x{1}y{1}|x{2}y{2}|x{3}y{3}|x{4}y{4})\b

https://regex101.com/r/vMl8vv/2

but this looks ugly and will result in a massive regex when the length is big.

Superluminal
  • 947
  • 10
  • 23