3

I have something like

store(s)

ending line like "1 store(s)". I want to match it using Python regular expression.

I tried something like re.match('store\(s\)$', text) but it's not working.

This is the code I tried:

import re

s = '1 store(s)'
if re.match('store\(s\)$', s):
    print('match')
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Jijoy
  • 12,386
  • 14
  • 41
  • 48

3 Answers3

6

In more or less direct reply to your comment

Try this

import re
s = '1 stores(s)'
if re.match('store\(s\)$',s):
    print('match')

The solution is to use re.search instead of re.match as the latter tries to match the whole string with the regexp while the former just tries to find a substring inside of the string that does match the expression.

poke
  • 369,085
  • 72
  • 557
  • 602
  • Also needed to add 'r' prefix to regex pattern string. – martineau Mar 14 '11 at 21:13
  • It's not a quote. The OP never said "Try this" and his code does not have `s = '1 stores(s)'`. I suggest you copy & paste for quotes...or be more careful typing it in, because otherwise your answer is very hard to understand. – martineau Mar 15 '11 at 08:59
  • @martineau: No, OP wrote that as a comment first, hence the “reply to your comment”. The actual message was then later put in the question and the comment was removed. That doesn’t change the fact that it is still a quote (and *not* my text)… – poke Mar 15 '11 at 13:40
1

Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default)

Straight from the docs, but it does come up alot.

Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
0

have you considered re.match('(.*)store\(s\)$',text) ?

Nate
  • 12,499
  • 5
  • 45
  • 60