0

Here's the code:

pattern = re.compile(r'ea') 
match = pattern.match('sea ea')
if match:
    print match.group()

the result is null. But when I change the code to pattern = re.compile(r'sea'), the output is "sea"

Could anyone give me an explanation?

p.s. Btw, What I want is to retrieve the "#{year}" from string "select * from records where year = #{year}", plz give me an usable regex. Thanks in advance!

Summary:

Thanks to ALL of u, I find it in the document of python with your instruction. since I can select only one most appropriate answer, I just give it to the one who answered most quickly. Thx again.

Judking
  • 6,111
  • 11
  • 55
  • 84

3 Answers3

2

You mean to use search, not match. match will match the regular expression only if it is at the start of the string.

pattern = re.compile(r'ea') 
match = pattern.search('sea ea')
if match:
    print match.group()
David Robinson
  • 77,383
  • 16
  • 167
  • 187
2

pattern.match is anchored at the beginning of the string.

You need pattern.search.

From the documentation:

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

devnull
  • 118,548
  • 33
  • 236
  • 227
0

match just matches, it doesn't search for things. This does:

>>> pattern = re.compile(r'(#{\w+})') 
>>> pattern.split('select * from records where year = #{year}')
['select * from records where year = ', '#{year}', '']
jhermann
  • 2,071
  • 13
  • 17