Match pattern for regex "subtraction" equations

Viewed 296

I want to match a valid "subtraction" equation of an unknown number (non-zero) of 'z' characters.

Valid string examples: "zzz-z=zz" or "zzzz-zzz=z"

Invalid string examples: "z-zz=z" or "zzz-z=z" or "z-zz=-z"

I have tried something like this, but it doesn't work. I believe it has to do with some sort of back-referencing?

re.match(r'(z+)\-(z+)\=(?!\2)\1', s)

Any help would be greatly appreciated.

2 Answers

It's really simple, don't overthink it.

Just break the first zs into 2 parts, and match the next two zs to the equation:

^(z+)(z+)-\1=\2$

Check the proof

This matches the first two strings ("zzz-z=zz" or "zzzz-zzz=z") without matching the last three ("z-zz=z" or "zzz-z=z" or "z-zz=-z").

(z{2,})\-(z{1})\=(z{2})|(z{2,})\-(z{3})\=(z{1})

The | is an or operator, so everything before it matches "zzz-z=zz" and everything after it matches "zzzz-zzz=z"

The curly braces are helpful for specifying a range of the number of times you want the character before them to match.

It may need adjusting if there are other valid string examples.

Related