regexp matching end of line or comma

Discussion in 'Python' started by Jean-Michel Pichavant, Nov 25, 2010.

  1. Hy guys,

    I'm struggling matching patterns ending with a comma ',' or an end of
    line '$'.

    import re

    ex1 = 'sumthin,'
    ex2 = 'sumthin'
    m1 = re.match('(?P<something>\S+),', ex1)
    m2 = re.match('(?P<something>\S+)$', ex2)
    m3 = re.match('(?P<something>\S+)[,$]', ex1)
    m4 = re.match('(?P<something>\S+)[,$]', ex2)

    print m1, m2
    print m3
    print m4

    <_sre.SRE_Match object at 0x8834de0> <_sre.SRE_Match object at 0x8834e20>
    <_sre.SRE_Match object at 0x8834e60>
    None

    My problem is that m4 is None while I'd like it to match ex2.

    Any clue ?

    JM
     
    Jean-Michel Pichavant, Nov 25, 2010
    #1
    1. Advertising

  2. Jean-Michel Pichavant

    Saul Spatz Guest

    On Nov 25, 8:40 am, Jean-Michel Pichavant <>
    wrote:
    > Hy guys,
    >
    > I'm struggling matching patterns ending with a comma ',' or an end of
    > line '$'.
    >
    > import re
    >
    > ex1 = 'sumthin,'
    > ex2 = 'sumthin'
    > m1 = re.match('(?P<something>\S+),', ex1)
    > m2 = re.match('(?P<something>\S+)$', ex2)
    > m3 = re.match('(?P<something>\S+)[,$]', ex1)
    > m4 = re.match('(?P<something>\S+)[,$]', ex2)
    >
    > print m1, m2
    > print m3
    > print m4
    >
    > <_sre.SRE_Match object at 0x8834de0> <_sre.SRE_Match object at 0x8834e20>
    > <_sre.SRE_Match object at 0x8834e60>
    > None
    >
    > My problem is that m4 is None while I'd like it to match ex2.
    >
    > Any clue ?
    >
    > JM


    From the Regular Expression Syntax documentation:
    Special characters are not active inside sets. For example, [akm$]
    will match any of the characters 'a', 'k', 'm', or '$';

    so in m4, [,$] matches a comma or a literal dollar sign.
     
    Saul Spatz, Nov 25, 2010
    #2
    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. Neo Geshel
    Replies:
    2
    Views:
    3,620
    Versteijn
    Aug 18, 2004
  2. William
    Replies:
    2
    Views:
    1,738
    Kevin Spencer
    Jun 1, 2005
  3. Neo Geshel

    "'If' must end with a matching 'End If'."

    Neo Geshel, Jul 3, 2004, in forum: ASP General
    Replies:
    0
    Views:
    139
    Neo Geshel
    Jul 3, 2004
  4. Joao Silva
    Replies:
    16
    Views:
    363
    7stud --
    Aug 21, 2009
  5. Rodrigo A B Freire

    Regexp-matching character n times in the line.

    Rodrigo A B Freire, Sep 22, 2004, in forum: Perl Misc
    Replies:
    3
    Views:
    118
    Rodrigo A B Freire
    Sep 23, 2004
Loading...

Share This Page