regexp matching end of line or comma

  • Thread starter Jean-Michel Pichavant
  • Start date
J

Jean-Michel Pichavant

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
 
S

Saul Spatz

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top