#!/usr/bin/python
#
import re, sys

str = "A programme description [internal comment] with flags and then something that follows. (Ep1/7). Then some flags... [HD] [S] Followed by The News [AD,S] Then Reporting Scotland."

(in1, in2, en) = sys.argv[1:4]

flags=r"\[[^[]*?\]"
incl_flags=[r"then+%s" % in1, r"followed by+%s" % in2]
excl_flags=[r"then+%s" % en]

# We wish to create a regex after parsing the user-supplied strings.
#
regex = []

flags_re = r"\[[^[]*?\]"
regex.append(flags_re)

def re_from_filters(filters, include_flags):   
        import re
#
        filt_re = []
	print "filters:", type(filters), filters
        for filt in filters:
		print "filt:", filt
                m = re.search(r"\+(\d+?)\s*$", filt)
                if m:
                        num = int((m.group(0))[1:])
                        strip = len(m.group(0))
                        act_re = filt[:-strip]   
                else:
                        num = 0
                        act_re = filt
                act_re = re.escape(act_re)
                if include_flags:
                        act_re = flags_re + r"\s*" + act_re
                if num > 0:
                        act_re += r".{,%d}" % num
                filt_re.append(act_re)
        return filt_re

if incl_flags:
    regex.extend(re_from_filters(incl_flags, True))
if excl_flags:
    regex.extend(re_from_filters(excl_flags, True))

# print regex

all_rex = "(" + "|".join(regex) + ")\s*$"
print all_rex

trimmer_re = re.compile(all_rex, flags=re.UNICODE|re.IGNORECASE)

sub_made = True
while sub_made:
    print "From:", str
    (str, sub_made) = re.subn(trimmer_re, '', str)
    print " to:", str

print str
