[Tutor] Re: lists in re?
Karl Pflästerer
sigurd at 12move.de
Tue Sep 9 23:25:32 EDT 2003
On 9 Sep 2003, Andreas Zwinkau <- andi at buxach.de wrote:
> If this gets more and more, i thought a dictionary would be the best way
> to define it in a obvious way. So this dict needs to be fed to the re
> module, but instead of processing each item, i wanted to re.compile it
> in one piece.
Did you think about writing it in a functional way? I took the regexps
from one one your previous postings to write the example.
[lambda string, x=reg, y=exp: re.compile(x).sub(y, string)
for (reg, exp) in
[ # (regexp, expansion)
("''(.+)''", r"<it>\1</it>"), # italic
(r"\*\*(.+)\*\*", r"<bold>\1</bold>"), #bold
("\[([\w \=\-\_\.]+)\]", r"<a href=\"\1\">\1</a>"), #link
("(?<=\n)\* (.*)\n", r"<ul><li>\1</li></ul>\n"), #list
("__(.+?)__", r"<u>\1</u>") # underline
]]
def wikinize (funs, stream):
for fun in funs:
stream = fun(stream)
return stream
We do here mainly two things:
( 1) We build a list of anonymous functions. Each function takes three
parameters: the string to be altered, a regular expression and an
expansion. The regexp and the expansion are taken from a list of
tuples (in each function they are bound to the correspondent values
from the tuples).
( 2) We write a function which takes a list of functions (our previously
build list) and a string.
here is an example
>>> s = "''abc''def**ghi**jkl[link]__underline__"
>>> flist =[lambda string, x=reg, y=exp: re.compile(x).sub(y, string)
... for (reg, exp) in
... [ # (regexp, expansion)
... ("''(.+)''", r"<it>\1</it>"), # italic
... (r"\*\*(.+)\*\*", r"<bold>\1</bold>"), #bold
... ("\[([\w \=\-\_\.]+)\]", r"<a href=\"\1\">\1</a>"), #link
... ("(?<=\n)\* (.*)\n", r"<ul><li>\1</li></ul>\n"), #list
... ("__(.+?)__", r"<u>\1</u>") # underline
... ]]
>>> wikinize(flist, s)
'<it>abc</it>def<bold>ghi</bold>jkl<a href=\\"link\\">link</a><u>underline</u>'
>>>
If you want to add new regexps and their expansions you only have to
change one list.
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list