Python Forum

Full Version: yes-no RE pattern swap
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

I'm trying to match the literal strings XX-11 or 11-XX using a Regular Expression in Python 3.6.5.
I thought that the yes/no pattern notation might be appropriate.
The re I came up with is:
import re
code1="xx-12"
code2="12-xx"
pattern = re.compile( r"(\d\d-)(?(1)\w{1,2}|\w{1,2}-\d\d)" )

match = pattern.match(code1)
if match:
  print(code1, " matches")
else:
  print(code1, " does not match")

match = pattern.match(code2)
if match:
  print(code2, " matches")
else:
  print(code2, " does not match")
I thought that I'd try and match \d\d- first off.
I then verify whether there has in fact been a match by specifying ?(1).
If matched then the word group would follow and it would end there.
If not matched then the 2 character \w{1,2} word followed by a dash and 2 digits would be matched.

code2 matches, but not code1. Could anybody help with this?
(Jun-07-2018, 10:00 PM)bluefrog Wrote: [ -> ]I then verify whether there has in fact been a match by specifying ?(1).

I suggest that you test your RE on https://regex101.com/ - besides testing, it also provides you with a full explanation of your RE structure.

I think that your problem - over-complication of the RE. It works just fine with a little simplification - (\d\d-\w{1,2}|\w{1,2}-\d\d)


Not that it is the case here, but numbered groups may get tricky in nested expressions - named group may be a better idea.