Find & Replace hyperlinks in a string

Discussion in 'Python' started by Nico Grubert, Nov 27, 2007.

  1. Nico Grubert

    Nico Grubert Guest

    Hi there,

    I have a string containing some hyperlinks. I'd like to replace every
    hyperlink with a HTML style link.

    Example:
    --------
    Replace
    'http://www.foo.com/any_url'
    with
    '<a href="http://www.foo.com/any_url">http://www.foo.com/any_url</a>'


    What's the best way to do this if I have a few hundret strings to check?

    Thanks in advance,
    Nico
     
    Nico Grubert, Nov 27, 2007
    #1
    1. Advertising

  2. Nico Grubert

    MonkeeSage Guest

    On Nov 27, 1:37 am, Nico Grubert <> wrote:
    > Hi there,
    >
    > I have a string containing some hyperlinks. I'd like to replace every
    > hyperlink with a HTML style link.
    >
    > Example:
    > --------
    > Replace
    > 'http://www.foo.com/any_url'
    > with
    > '<a href="http://www.foo.com/any_url">http://www.foo.com/any_url</a>'
    >
    > What's the best way to do this if I have a few hundret strings to check?
    >
    > Thanks in advance,
    > Nico


    Well, this isn't the most robust and someone will probably say not to
    use regular expressions, but the Q&D way is:

    import re
    fixed = re.sub(r'(http:[^\s\n\r]+)', r'<a href="\1">\1</a>',
    your_string)

    NB. If the URLs are malformed (like have spaces in them, or are broken
    over several lines) this won't work right.

    Regards,
    Jordan
     
    MonkeeSage, Nov 27, 2007
    #2
    1. Advertising

  3. Nico Grubert

    gsal Guest

    You mean in Python? 'cause if it is a one time shot kind of thing, I
    would simply open the file in my favorite editor (NEdit) and use a
    Search and Replace, check the regexp box and type my
    expression...something along the lines of ([^:]+)://([^:/]+):)
    ([0-9]+))?(/.*) to find URLs and then replace with <a href="\0">\0</
    a> ...if I remember correctly that \0 is the entire match, \1 the
    first parenthesised match, etc.

    gsal
     
    gsal, Nov 27, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Xah Lee
    Replies:
    0
    Views:
    650
    Xah Lee
    Jun 14, 2006
  2. hokieghal99

    String find and replace

    hokieghal99, Aug 27, 2003, in forum: Python
    Replies:
    10
    Views:
    721
    hokiegal99
    Aug 27, 2003
  3. Alun
    Replies:
    3
    Views:
    4,649
    Masudur
    Feb 18, 2008
  4. Prasad S
    Replies:
    2
    Views:
    257
    Dr John Stockton
    Aug 27, 2004
  5. V S Rawat
    Replies:
    5
    Views:
    345
    Richard Cornford
    Jul 3, 2007
Loading...

Share This Page