Reputation: 16691
I have the following class. But when trying to pass the variable x to the re.match it doesnt appear to correctly work as whatever input I put in it returns "invalid"
class validate:
def __init__(self, input_value):
self.input_value = input_value
def macaddress(self, oui):
self.oui = oui
#oui = 0, input deemed valid if it matches {OUI:DEVICE ID}.
#oui = 1, input deemed valid if it matches {OUI}.
if self.oui == 0:
x = 5
elif self.oui == 1:
x = 2
if re.match("[0-9a-fA-F]{2}([.-: ][0-9a-fA-F]{2}){x}$", self.input_value):
return "valid"
else:
return "invalid"
Should I be passing var x in some other manner ?
Thanks,
Upvotes: 1
Views: 124
Reputation: 78600
Insert x
into the string this way (using string formatting):
Python <2.7:
if re.match("[0-9a-fA-F]{2}([.-: ][0-9a-fA-F]{2}){%d}$" % x, self.input_value):
However if you use the python 3 way of formatting, your regex interferes.
It can be cleaner (but slower) to use concatenation.
Without concatenation:
if re.match("[0-9a-fA-F]\{2\}([.-: ][0-9a-fA-F]\{2\}){0}$".format(x), self.input_value):
With concatenation:
if re.match("[0-9a-fA-F]{2}([.-: ][0-9a-fA-F]{2})" + x + "$", self.input_value):
Note: this fails if implicit type conversion is not possible.
If you just put {x}
in the middle of your string, Python doesn't actually do anything with it unless string formatting is applied.
Upvotes: 5