2

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.

1
  • 1
    If the question is too general, it's likely to be closed. Try to gather your thoughts and attempts together and show us what you've come up with. Although I've seen this sort of problem in Theory of Computation books before - the general idea is you have some token in your alphabet sandwiching an unchanging token. Commented Nov 27, 2012 at 5:10

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The pyparsing published examples include a regex inverter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.