Note that there are some explanatory texts on larger screens.

plurals
  1. POI'm using Python regexes in a criminally inefficient manner
    primarykey
    data
    text
    <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p> <p>This input:</p> <blockquote> The Web </blockquote> <p>Should produce this output:</p> <blockquote> <p>The Web This Is A Test Variable</p> </blockquote> <p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p> <p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p> <pre><code>def stripMatchedQuotes(item): MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE) MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE) item = MatchedSingleQuotes.sub(r'\1', item, 1) item = MatchedDoubleQuotes.sub(r'\1', item, 1) return item def processVariables(item): VariableDefinition = re.compile(r'&lt;%(.*?)=(.*?)%&gt;', re.LOCALE) VariableUse = re.compile(r'&lt;%(.*?)%&gt;', re.LOCALE) Variables={} while VariableDefinition.search(item): VarName, VarDef = VariableDefinition.search(item).groups() VarName = stripMatchedQuotes(VarName).upper().strip() VarDef = stripMatchedQuotes(VarDef.strip()) Variables[VarName] = VarDef item = VariableDefinition.sub('', item, 1) while VariableUse.search(item): VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip() item = VariableUse.sub(Variables[VarName], item, 1) return item </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload