Reputation: 1979
I am looking for an algorithm or some advices to implement it.
Input:
"{1|2} word {3|4}"
Output:
["1 word 3", "1 word 4", "2 word 3", "2 word 4"]
Also, i want to support nested constructions - "{1|2{0|1}}" -> ["1", "20", "21"]
I realize that the question is too general, but don't want to implement the wheel. Maybe you saw similar things.
UPD
from pyparsing import *
from collections import deque
s = u"{1|2} {3|4}"
deque = deque()
def mesh_lists(listOne, listTwo):
result = []
for l1 in listOne:
for l2 in listTwo:
firstWord = str(l1).strip()
secondWord = str(l2).strip()
result.append(" " + firstWord + " " + l2 + " ")
return result
def action(string, pos, token):
global deque
deque.append(list(token[0]))
def processDeque():
global deque
while len(deque) > 1:
l1 = deque.popleft()
l2 = deque.popleft()
res = mesh_lists(l1,l2)
deque.appendleft(res)
return [x.strip() for x in deque[0]]
_lcurl = Suppress('{')
_rcurl = Suppress('}')
_pipe = Suppress('|')
word = Regex("[^{|}]+")
varBlock = Forward()
entry = word | varBlock
varList = Group(entry + ZeroOrMore(_pipe + entry))
varBlock << (_lcurl + Optional(varList) + _rcurl).setParseAction(action)
template = ZeroOrMore(entry)
res = template.parseString(s)
print processDeque()
It supports only "{||}{||}" constructions. No barewords, no nested constructions.
Upvotes: 2
Views: 451
Reputation: 30736
This project looks suitable for you: https://github.com/asciimoo/exrex
Exrex is a tool that generates all matching strings to a given regular expression.
Upvotes: 4