Finding the carret position in a regular expression

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

    #1

    Finding the carret position in a regular expression

    Hi,
    supposed I've got the following text :

    mytext = "for <myvarin <somelist>:"

    with the following simple pattern : pattern = "<[a-z]+>"

    I use re.findall(patt ern, mytext) wich returns :
    ['<myvar>','<som elist>']

    Now, I want my prog to return the positions of the returned list
    elements, ie :
    <myvarwas found at position 5 in mytext
    <somelistwas found at position 16 in mytext

    How can I implement this ? Sorry if it's trivial, that's the first time
    I use regular expressions.
    Thanks,
    6Tool9

  • Fredrik Lundh

    #2
    Re: Finding the carret position in a regular expression

    Tool69 wrote:
    supposed I've got the following text :
    >
    mytext = "for <myvarin <somelist>:"
    >
    with the following simple pattern : pattern = "<[a-z]+>"
    >
    I use re.findall(patt ern, mytext) wich returns :
    ['<myvar>','<som elist>']
    >
    Now, I want my prog to return the positions of the returned list
    elements, ie :
    <myvarwas found at position 5 in mytext
    <somelistwas found at position 16 in mytext
    "findall" doesn't return that information; use "finditer" instead, and
    use the "span" or "start" method on the returned match object to get the
    position:

    for m in re.finditer(pat tern, mytext):
    print m.span()

    </F>

    Comment

    • Tool69

      #3
      Re: Finding the carret position in a regular expression

      Thanks Fredrik,
      I was not aware of finditer. Iterators are very usefull !

      Comment

      Working...