Question about parsing a string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Nico Grubert

    #1

    Question about parsing a string

    Hi there,

    I would like to parse a string in Python.

    If the string is e.g. '' I would like
    to generate this string:
    '<a href="http://www.whatever.or g">http://www.whatever.or g</a>'

    If the string is e.g. 'My link' I
    would like to generate this string:
    '<a href="http://www.whatever.or g">My link</a>'

    Any idea how I can do this? Maybe with regular expressions?

    Thanks in advance,
    Nico
  • Alex Martelli

    #2
    Re: Question about parsing a string

    Nico Grubert <nicogrubert@gm ail.com> wrote:
    [color=blue]
    > Hi there,
    >
    > I would like to parse a string in Python.
    >
    > If the string is e.g. '' I would like
    > to generate this string:
    > '<a href="http://www.whatever.or g">http://www.whatever.or g</a>'
    >
    > If the string is e.g. 'My link' I
    > would like to generate this string:
    > '<a href="http://www.whatever.or g">My link</a>'
    >
    > Any idea how I can do this? Maybe with regular expressions?[/color]

    If you know the string always starts with '[url=' and ends with '[/url]'
    (or, any string not thus starting/ending are to be skipped, etc), REs
    are a bit of an overkill (they'll work, but you can do it more simply).

    If your actual needs are different, you'll have to express them more
    explicitly. But assuming the "given starting and ending" scenario:

    _start = '[url='
    _startlen = len(_start)
    _end = '[/url]'
    _endlen = len(_end)
    def doit(s):
    if s[:_startlen] != _start: raise ValueError
    if s[-_endlen:] != _end: raise ValueError
    where_closebrac ket = s.index(']')
    url = s[_startlen:where _closebracket]
    txt = s[where_closebrac ket+1:-_endlen]
    if not txt: txt = url
    return '<a href="%s">%s</a>' % (url, txt)

    I've just typed in this code without trying it out, but roughly it
    should be what you want.


    Alex

    Comment

    Working...