[Tutor] regular expression

Andrew McNamara andrewm at object-craft.com.au
Thu Feb 12 22:30:17 EST 2004


>What is the fastest way to search for a string and then surround it
><code> and </code> with something. Like so:
>
>x = '<div> are not allowed, these arent either <br>'
><some code here>
>x = '<code><div></code> are not allowed, these arent either
><code><br></code>'
>
>The two ways this can be done is by subsituting the string like <div>
>with <code><div></code> or inserting <code> and </code> before and after
>it. Which one would be faster and how would I do it? I got as far as
>creating the regular expression r'<[^<>]*>'

"Obviously correct" is usually more important than "fastest", so don't
get too worried by which way is faster until you need a faster way.

Here's one way to do what you want. Note that I'm also replacing the <
and > in the quoted block, and note the use of a raw string for the
replacement string - you could also double the backslash and use a
regular string:

    re.sub('<([^>]*)>', r'<code>&lt;\1&gt;</code>', x)

If you *really* want the exact results you mention, then:

    re.sub('(<[^>]*>)', r'<code>\1</code>', x)

-- 
Andrew McNamara, Senior Developer, Object Craft
http://www.object-craft.com.au/



More information about the Tutor mailing list