Reputation: 4130
I am trying to make arguments easier to manage in a script I am putting together, I figured I'd wrap a bunch of related items into a dictionary, and pass the dictionary out of the func. pulling out the objects as I need them.
One of these items is a regEx, and I'm struggling to figure out how to structure things properly so I can make it work.
In my initial code (no dictionary). I am 'hard' coding the regex into the parser:
def TopnTail(self,line):
topRegEx = re.compile(r'(<!--make_database header end-->)')
tailRegEx = re.compile(r'(<!--make_database footer start-->)')
searchdumpTopOfPage = topRegEx.search(line)
searchdumpBottomOfPage = tailRegEx.search(line)
if searchdumpTopOfPage:
self.__useLine=1
if searchdumpBottomOfPage:
self.__useLine=0
if self.__useLine == 1:
self.trimmedLines = self.trimmedLines + line + "\n"
return (self.trimmedLines)
in the 'dictionaried' version I want to set the variables in a setter:
def siteDetails():
baseDict = {'topRegex':'''re.compile(r'(<!--make_database header end-->)')''', 'tailRegex':'''re.compile(r'(<!--make_database footer start-->)')'''}
return baseDict
and get to the compiled regex:
def TopnTail(self,line):
topRegEx = baseDict['topRegex']
tailRegEx = baseDict['tailRegex']
searchdumpTopOfPage = topRegEx.search(line)
searchdumpBottomOfPage = tailRegEx.search(line)
if searchdumpTopOfPage:
self.__useLine=1
if searchdumpBottomOfPage:
self.__useLine=0
if self.__useLine == 1:
self.trimmedLines = self.trimmedLines + line + "\n"
return (self.trimmedLines)
but this throws an error:
line 35, in TopnTail
searchdumpTopOfPage = topRegEx.search(line)
AttributeError: 'str' object has no attribute 'search'
Which I am guessing means that its not actually made the regex object, but is still passing the string.
I appreciate that I am probably breaking about 3 cardinal rules here... but any suggestions about how to make it work would be fantastic... (also, first time playing with both classes and dictionaries... so please go easy if I've really messed up!)
Upvotes: 0
Views: 158
Reputation: 18850
How about this?
baseDict = {
'topRegex': r'(<!--make_database header end-->)'
}
And in your TopnTail
method
topRegEx = re.compile(baseDict['topRegex'])
The problem with what you have, is that you're assigning a string to topRegEx that contains '''re.compile(r'(<!--make_database header end-->)')'''
. Since str
has no method search
, you get an error.
It makes sense to still compile your regex, and use the returned object. Splitting the contents of the regex into a dict will help if you ever need to changes the regex pattern, or you want to define it dynamically.
Upvotes: 1