Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
yes-no RE pattern swap
#1
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?
Reply
#2
(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.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to swap two numbers in fields in python Joni_Engr 5 1,804 Jan-11-2022, 09:43 AM
Last Post: menator01
  Swap key and value of a dictionary - and sort it Omid 4 2,799 Oct-28-2020, 01:24 PM
Last Post: Omid
  swap elements in list hshivaraj 3 12,479 Apr-22-2019, 09:23 AM
Last Post: Yoriz
  I am trying to swap two variables with a Function.... Jeff_Waldrop 4 3,045 Mar-04-2019, 10:19 AM
Last Post: Jeff_Waldrop
  Randomise network while maintaining topology of nodes using edge-swap approach Tom1988 3 4,063 May-25-2017, 10:59 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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