Regex question

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

    Regex question

    I've a perhaps unusual piece of data to parse with regexes.
    [color=blue][color=green][color=darkred]
    >>> import re
    >>> re.findall("a (\w ?)*", "a b c d e f g h")[/color][/color][/color]
    ['h']

    This is a very very very simplified example. The result I was
    expecting is the following: ['a', 'b', 'c'] ... and so forth. Is it
    impossible to repeat a pattern group inside another?


    Tia,



    \\ jonas galvez
    // jonasgalvez.com





  • Luke

    #2
    Re: Regex question

    Jonas Galvez wrote:[color=blue]
    > I've a perhaps unusual piece of data to parse with regexes.
    >
    >[color=green][color=darkred]
    >>>>import re
    >>>>re.findall( "a (\w ?)*", "a b c d e f g h")[/color][/color]
    >
    > ['h']
    >
    > This is a very very very simplified example. The result I was
    > expecting is the following: ['a', 'b', 'c'] ... and so forth. Is it
    > impossible to repeat a pattern group inside another?[/color]

    Are you hoping for your regular expression to match the whole string, or
    just one letter? This is how I would get the result you seek:
    [color=blue][color=green][color=darkred]
    >>> import re
    >>> re.findall("\w" , "a b c d e f g h")[/color][/color][/color]
    ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

    The regular expression you used, "a (\w ?)*", will match the whole string,
    which is why you have only one element in the list returned by findall.
    Since you used a group (using parentheses), findall only returned what was
    inside the group (the 'h') rather than the whole match ('a b c d e f g h').

    Comment

    Working...