regular expression in strings

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

    regular expression in strings

    I'm trying to understand how regex's are interpreted out of strings
    objects. for example, If I have a string that has newline chars in
    it, how can I get a re.split to respect where the newlines are?
    [color=blue][color=green][color=darkred]
    >>> bs = 'in the begining, \n there were new lines, and in the end \nin lines'
    >>> re.split('^in', bs)[/color][/color][/color]
    ['', ' the begining, \n there were new lines, and in the end \nin lines'][color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

    I want to split the string bs. a '^in' should have also match \nin
    where \n is the newline char.

    Ultimately I have a large string buffer that I want to split at each
    occurence of a particular regular expression, where the result
    contains everything from the occurence of the regex till the end of
    the 'line'

    any pointers?

    David Bear
    phone: 480-965-8257
    fax: 480-965-9189
    College of Public Programs/ASU
    Wilson Hall 232
    Tempe, AZ 85287-0803
    "Beware the IP portfolio, everyone will be suspect of trespassing"

  • David M. Cooke

    #2
    Re: regular expression in strings

    At some point, David Bear <david.bear@asu .edu> wrote:
    [color=blue]
    > I'm trying to understand how regex's are interpreted out of strings
    > objects. for example, If I have a string that has newline chars in
    > it, how can I get a re.split to respect where the newlines are?
    >[color=green][color=darkred]
    >>>> bs = 'in the begining, \n there were new lines, and in the end \nin lines'
    >>>> re.split('^in', bs)[/color][/color]
    > ['', ' the begining, \n there were new lines, and in the end \nin lines'][color=green][color=darkred]
    >>>>[/color][/color]
    >
    > I want to split the string bs. a '^in' should have also match \nin
    > where \n is the newline char.[/color]

    Just amounts to reading the documentation for the re module; what you want is[color=blue][color=green][color=darkred]
    >>> re.split('(?m)^ in', bs)[/color][/color][/color]
    ['', ' the begining, \n there were new lines, and in the end \n', ' lines']

    The (?m) construct says 'set flag re.M for this expression', where
    re.M == re.MULTILINE is the flag to have ^ match the beginning of
    the string and the beginning of each line (similiar for $).

    It's a bit clearer with compiled patterns:[color=blue][color=green][color=darkred]
    >>> pat = re.compile('^in ', re.MULTILINE)
    >>> pat.split(bs)[/color][/color][/color]
    ['', ' the begining, \n there were new lines, and in the end \n', ' lines']

    --
    |>|\/|<
    /--------------------------------------------------------------------------\
    |David M. Cooke
    |cookedm(at)phy sics(dot)mcmast er(dot)ca

    Comment

    Working...